C++实现两个数的各种运算功能
实现思路:
先写一个基础类。从这个基础类上继承写出各个运算的类
多态的条件:
1.有继承
2.子类重写了父类的虚函数(加了关键字virtual的函数是虚函数)
3.父类的指针或引用指向了子类的函数
多态的优点:
1。代码组织结构清晰
2.可读性强
3.利于前期和后期的扩展以及维护
代码:
#include<iostream>
using namespace std;
class AbstractCalculator {
public:
virtual double getresult() {//加了关键字virtual的函数是虚函数
return 0;
}
int m_num1;
int m_num2;
};
class AddCalculator:public AbstractCalculator {//加法类
double getresult() {
return m_num1 + m_num2;
}
};
class SubtractionCalculator :public AbstractCalculator {//减法类
double getresult() {
return m_num1 - m_num2;
}
};
class MulCalculator :public AbstractCalculator {//乘法类
double getresult() {
return m_num1 * m_num2;
}
};
class DivCalculator :public AbstractCalculator {//除法类
double getresult() {
return m_num1 /m_num2;
}
};
//后续如果再想写其他运算,按照上面的继续写就可以
int main() {
AbstractCalculator* num = new AddCalculator;//父类的指针指向了声明的加法类的对象;
num->m_num1 = 10; num->m_num2 = 10;
cout<<num->m_num1<<"+"<<num->m_num2<<"="<< num->getresult()<<endl;//测试加法类
//因为用new关键字声明了一个新对象,所以需要手动释放
delete num;
num = new SubtractionCalculator;//父类的指针指向了声明的减法类的对象;
num->m_num1 = 10; num->m_num2 = 10;
cout << num->m_num1 << "-" << num->m_num2 << "=" << num->getresult() << endl;//测试减法类
//因为用new关键字声明了一个新对象,所以需要手动释放
delete num;
num = new MulCalculator;//父类的指针指向了声明的乘法类的对象;
num->m_num1 = 10; num->m_num2 = 10;
cout << num->m_num1 << "*" << num->m_num2 << "=" << num->getresult() << endl;//测试乘法类
//因为用new关键字声明了一个新对象,所以需要手动释放
delete num;
num = new DivCalculator;//父类的指针指向了声明的除法类的对象;
num->m_num1 = 10; num->m_num2 = 10;
cout << num->m_num1 << "/" << num->m_num2 << "=" << num->getresult() << endl;//测试除法类
//因为用new关键字声明了一个新对象,所以需要手动释放
delete num;
}
运行结果截图: