案例:使用多态实现一个简单的计算器,计算两个数的加减乘除结果
分析:定义一个抽象类AbstractCalc ,其内部定义一个纯虚函数getResult,用于得到计算结果
定义加减乘除四个类,分别继承这个抽象类AbstractCalc,重写内部的纯虚函数getResult,只不过根据各种需求重新内容不同而已
最后可以通过父类指针指向子类对象进行调用加减乘除各自对父类的纯虚函数重写后的getResult函数即可
#include<iostream>
class AbstractCalc
{
public:
virtual int getResult() = 0;
int m_num1;
int m_num2;
};
class AddCal :public AbstractCalc
{
public:
virtual int getResult()
{
return m_num1 + m_num2;
}
};
class SubCal :public AbstractCalc
{
public:
virtual int getResult()
{
return m_num1 - m_num2;
}
};
class MulCal :public AbstractCalc
{
public :
virtual int getResult()
{
return m_num1 * m_num2;
}
};
class DivCal :public AbstractCalc
{
public:
virtual int getResult()
{
return m_num1 / m_num2;
}
};
int main()
{
AbstractCalc *calc = new AddCal;
calc->m_num1 = 100;
calc->m_num2 = 20;
std::cout << calc->getResult() << std::endl;//100+20=120
delete calc;
AbstractCalc* calc1 = new SubCal;
calc1->m_num1 = 10;
calc1->m_num2 = 20;
std::cout << calc1->getResult() << std::endl;//10-20=-10
delete calc1;
//乘除自己去实现就行,注意除法分母不为0等一些小细节
return 0;
}
运行效果: