donmike25

MIDTERM 2_2

Jan 11th, 2015
374
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.82 KB | None | 0 0
  1. QUESTION 2
  2.  
  3. #include <iostream>
  4. using namespace std;
  5.  
  6. class ILogic{
  7. public:
  8.     virtual long Compute(long input1, long input2) = 0;
  9. };
  10.  
  11. class XOR :public ILogic{
  12. public:
  13.     long Compute(long input1, long input2){
  14.         return input1 ^ input2;
  15.     }
  16. };
  17.  
  18. class NOR :public ILogic{
  19. public:
  20.     long Compute(long input1, long input2){
  21.         return ~(input1 | input2);
  22.     }
  23. };
  24.  
  25. class NAND :public ILogic{
  26. public:
  27.     long Compute(long input1, long input2){
  28.         return ~(input1 & input2);
  29.     }
  30. };
  31.  
  32. class Logic{
  33.     ILogic *m_pObject;
  34.     long m_Input1, m_Input2;
  35. public:
  36.     void SetAttributes(long in1, long in2){
  37.         m_Input1 = in1;
  38.         m_Input2 = in2;
  39.     }
  40.     void SetLogicObject(ILogic *pObject){
  41.         m_pObject = pObject;
  42.     }
  43.     void ComputeLogic(long &result){
  44.         result = m_pObject->Compute(m_Input1, m_Input2);
  45.     }
  46. };
  47.  
  48. // Note: Implement parts (a) & (b) as per the requirements of QUESTION_2.
  49. int main()
  50. {
  51.     int type;
  52.     long in1, in2, result;
  53.     ILogic *a = NULL;
  54.     Logic b;
  55.     while(1){
  56.         cout << "Specify a logic operation" << endl << "(0 --> XOR, 1 --> NOR, 2 --> NAND, -1 --> exit): ";
  57.         cin >> type;
  58.         if (type == -1){
  59.             cout << endl << "Program terminated." << endl;
  60.             return 0;
  61.         }
  62.         if (type == 0 || type == 1 || type == 2){
  63.             cout << endl << "Enter two integer logic inputs: ";
  64.             cin >> in1 >> in2;
  65.             if (type == 0){
  66.                 a = new XOR;
  67.                 b.SetAttributes(in1, in2);
  68.                 b.SetLogicObject(a);
  69.                 b.ComputeLogic(result);
  70.             }
  71.             else if (type == 1){
  72.                 a = new NOR;
  73.                 b.SetAttributes(in1, in2);
  74.                 b.SetLogicObject(a);
  75.                 b.ComputeLogic(result);
  76.             }
  77.             else if (type == 2){
  78.                 a = new NAND;
  79.                 b.SetAttributes(in1, in2);
  80.                 b.SetLogicObject(a);
  81.                 b.ComputeLogic(result);
  82.             }
  83.             cout << endl << "Output: " << result << endl << endl;
  84.         }
  85.         else
  86.             cout << endl << "Invalid Input" << endl << endl;
  87.     }
  88.     return 0;
  89. }
Advertisement
Add Comment
Please, Sign In to add comment