donmike25 icon

MIDTERM 2_2

donmike25 | PRO | 01/11/15 10:43:44 AM UTC | 0 ⭐ | 348 👁️ | Never ⏰ | []
C++ |

1.82 KB

|

None

|

0 👍

/

0 👎

QUESTION 2
 
#include <iostream>
using namespace std;
 
class ILogic{
public:
    virtual long Compute(long input1, long input2) = 0;
};
 
class XOR :public ILogic{
public:
    long Compute(long input1, long input2){
        return input1 ^ input2;
    }
};
 
class NOR :public ILogic{
public:
    long Compute(long input1, long input2){
        return ~(input1 | input2);
    }
};
 
class NAND :public ILogic{
public:
    long Compute(long input1, long input2){
        return ~(input1 & input2);
    }
};
 
class Logic{
    ILogic *m_pObject;
    long m_Input1, m_Input2;
public:
    void SetAttributes(long in1, long in2){
        m_Input1 = in1;
        m_Input2 = in2;
    }
    void SetLogicObject(ILogic *pObject){
        m_pObject = pObject;
    }
    void ComputeLogic(long &result){
        result = m_pObject->Compute(m_Input1, m_Input2);
    }
};
 
// Note: Implement parts (a) & (b) as per the requirements of QUESTION_2.
int main()
{
    int type;
    long in1, in2, result;
    ILogic *a = NULL;
    Logic b;
    while(1){
        cout << "Specify a logic operation" << endl << "(0 --> XOR, 1 --> NOR, 2 --> NAND, -1 --> exit): ";
        cin >> type;
        if (type == -1){
            cout << endl << "Program terminated." << endl;
            return 0;
        }
        if (type == 0 || type == 1 || type == 2){
            cout << endl << "Enter two integer logic inputs: ";
            cin >> in1 >> in2;
            if (type == 0){
                a = new XOR;
                b.SetAttributes(in1, in2);
                b.SetLogicObject(a);
                b.ComputeLogic(result);
            }
            else if (type == 1){
                a = new NOR;
                b.SetAttributes(in1, in2);
                b.SetLogicObject(a);
                b.ComputeLogic(result);
            }
            else if (type == 2){
                a = new NAND;
                b.SetAttributes(in1, in2);
                b.SetLogicObject(a);
                b.ComputeLogic(result);
            }
            cout << endl << "Output: " << result << endl << endl;
        }
        else
            cout << endl << "Invalid Input" << endl << endl;
    }
    return 0;
}

Comments