#include<iostream>//本题使用的是继承和多态 #include<string> #include<cstring> using namespace std; class Base//父类,抽象类 { public://不能用private,用private下面的子类就无法继承变量了 int x; int y; public: Base(int x, int y)//构造函数初始化 { this->x = x; this->y = y; } virtual int getresult() = 0;//纯虚函数 }; class Add : public Base//Add类 { public: Add(int x, int y) :Base(x, y) {}//构造函数初始化 virtual int getresult()//使用Base类的变量 { return x + y; } }; class Sub :public Base//SUB类 { public: Sub(int x, int y) :Base(x, y) {} virtual int getresult() { return x - y; } }; class Mul :public Base//Mul类 { public: Mul(int x, int y) :Base(x, y) {} virtual int getresult() { return x * y; } }; class Div :public Base//Div类 { public: Div(int x, int y) :Base(x, y) {} virtual int getresult() { return x / y; } }; int main() { string p; int x, y; //实现多行输入,输入为0或换行符时结束 cin >>p >> x >> y; getchar();//吸收y后面敲出的换行符 if (p == "add" || p == "Add" || p == "ADD" || p == "ADd" || p == "adD" || p == "aDd" || p == "AdD" || p == "aDD") { Add A(x, y); Base* B =& A;//使用父类指针指向子类,先初始化A再使用指针 cout << B->getresult(); } else if (p == "sub" || p == "suB" || p == "sUb" || p == "sUB" || p == "SUb" || p == "SUB" || p == "SuB" || p == "Sub") { Base* B = new Sub(x, y);//直接使用父类指针指向子类 cout << B->getresult(); } else if (p == "mul" || p == "muL" || p == "mUl" || p == "mUL" || p == "Mul" || p == "MuL" || p == "MUL" || p == "MUl") { Base* B = new Mul(x, y); cout << B->getresult();//同理 } else { Base* B = new Div(x, y);//除法的判断分母 if (y == 0) { cout << "Error"; } else cout << B->getresult(); } getchar();//为了美观吸收输出后的换行符 }