#include <iostream>
using namespace std;
//利用多态实现计算器
//实现计算器抽象类
class abstructCalculator {
public:
virtual int getResult() {//将getResult函数抽象出来
return 0;
}
int m_num1;
int m_num2;
};
//加法计算器类
class addCalculator : public abstructCalculator {//继承抽象类
public:
virtual int getResult() {//重写getResult函数
return m_num1 + m_num2;
}
};
//减法计算器类
class subCalculator : public abstructCalculator {
public:
virtual int getResult() {
return m_num1 - m_num2;
}
};
//乘法计算器类
class mulCalculator : public abstructCalculator {
public:
virtual int getResult() {
return m_num1 * m_num2;
}
};
void test() {
//多态的使用条件:父类指针或引用指向类对象
abstructCalculator *abc = new addCalculator;
abc->m_num1 = 28;
abc->m_num2 = 34;
cout << abc->m_num1 << "+" << abc->m_num2 << "=" << abc->getResult() << endl;
delete abc;//将堆区的数据销毁
abc = new subCalculator;
abc->m_num1 = 28;
abc->m_num2 = 34;
cout << abc->m_num1 << "-" << abc->m_num2 << "=" << abc->getResult() << endl;
delete abc;
abc = new mulCalculator;
abc->m_num1 = 28;
abc->m_num2 = 34;
cout << abc->m_num1 << "*" << abc->m_num2 << "=" << abc->getResult() << endl;
delete abc;
}
int main() {
test();
getchar();
return 0;
}
多态的使用条件:父类指针或引用指向类对象:abstructCalculator *abc = new addCalculator;,new完记得要delete,删除的是abc指向的堆区。