学习记录:应用C++的多态实现加减乘除。
class AbstractCaltator
{
public:
virtual int get_Result()
{
return 0;
}
int num_1;
int num_2;
};
//加法
class AddCaltator :public AbstractCaltator//子类继承父类
{
public:
int get_Result()
{
return num_1 + num_2;
}
};
//减法
class SubCaltator :public AbstractCaltator
{
public:
int get_Result()
{
return num_1 - num_2;
}
};
//乘法
class MulCaltator :public AbstractCaltator
{
public:
int get_Result()
{
return num_1 * num_2;
}
};
//除法
class CHU_Caltator :public AbstractCaltator
{
public:
int get_Result()
{
return num_1 / num_2;
}
};
void test()
{
//用父类的指针实现加法运算
AbstractCaltator* abc = new AddCaltator;
abc->num_1 = 10;
abc->num_2 = 10;
cout << abc->num_1 << "+" << abc->num_2 << "=" << abc->get_Result() << endl;
delete abc;
AbstractCaltator* abc = new SubCaltator;
abc->num_1 = 10;
abc->num_2 = 10;
cout << abc->num_1 << "-" << abc->num_2 << "=" << abc->get_Result() << endl;
delete abc;
AbstractCaltator* abc = new MulCaltator;
abc->num_1 = 10;
abc->num_2 = 10;
cout << abc->num_1 << "*" << abc->num_2 << "=" << abc->get_Result() << endl;
delete abc;
AbstractCaltator* abc = new CHU_Caltator;
abc->num_1 = 10;
abc->num_2 = 10;
cout << abc->num_1 << "/" << abc->num_2 << "=" << abc->get_Result() << endl;
delete abc;
}
int main()
{
test();
system("pause");
return 0;
}