案例:使用多态实现一个简单的计算器,计算两个数的加减乘除结果
分析:定义一个抽象类AbstractCalc ,其内部定义一个纯虚函数getResult,用于得到计算结果
定义加减乘除四个类,分别继承这个抽象类AbstractCalc,重写内部的纯虚函数getResult,只不过根据各种需求重新内容不同而已
最后可以通过父类指针指向子类对象进行调用加减乘除各自对父类的纯虚函数重写后的getResult函数即可
#include<iostream>
class AbstractCalc
{
public:virtual int getResult() = 0;int getNum1() {return m_num1;}int getNum2(){return m_num2;}void setNum1(int num){m_num1 = num;}void setNum2(int num){m_num2 = num;}private:int m_num1;int m_num2;
};class AddCal :public AbstractCalc
{
public:virtual int getResult(){return getNum1() + getNum2();}};
class SubCal :public AbstractCalc
{
public:virtual int getResult(){return getNum1() - getNum2();}};class MulCal :public AbstractCalc
{
public :virtual int getResult(){return getNum1() * getNum2();}};class DivCal :public AbstractCalc
{
public:virtual int getResult(){return getNum1() / getNum2();}};int main()
{AbstractCalc *calc_add = new AddCal;calc_add->setNum1(10);calc_add->setNum2(20);std::cout << calc_add->getResult() << std::endl;//10+20=30delete calc_add;AbstractCalc* calc_sub = new SubCal;calc_sub->setNum1(20);calc_sub->setNum2(2);std::cout << calc_sub->getResult() << std::endl;//20-2=18delete calc_sub;//乘除里面有一些小细节,这里只是为了距离更好理解多态,具体小细节就不再赘述了,自己可以去完善实现,注意除法分母不为0等一些小细节AbstractCalc* calc_mul = new MulCal;calc_mul->setNum1(2);calc_mul->setNum2(2);std::cout << calc_mul->getResult() << std::endl;//2*2=4delete calc_mul;AbstractCalc* calc_div = new DivCal;calc_div->setNum1(18);calc_div->setNum2(9);std::cout << calc_div->getResult() << std::endl;//18/9=2delete calc_div;return 0;
}
运行效果: