#include<iostream>
using namespace std;
class yunsuan{
public:
virtual int getchuchu(){
return 0;
}
int a;
int b;
};
//实现加法运算
class jiafa :public yunsuan{
public:
int getchuchu(){
return a+b;
}
};
//实现减法运算
class jianfa :public yunsuan{
public:
int getchuchu(){
return a-b;
}
};
//实现乘法运算
class chengfa : public yunsuan{
public:
int getchuchu(){
return a*b;
}
};
//实现除法运算
class chufa : public yunsuan{
public:
int getchuchu(){
if ((a == 0 && b == 0)||a==0||b==0){
cout << "输出错误数据";
return -1;
}
return a/b;
}
};
void test(){
//加法测试
yunsuan *p = new jiafa;
p->a = 10;
p->b = 20;
cout << "两数相加为:"<<p->getchuchu() << endl;
//除法测试
p = new chufa;
p->a = 20;
p->b = 20;
cout <<"两个数相除为:"<< p->getchuchu() << endl;
}
int main(){
test();
}
c++多态案例题1:用多态实现简单运算器
最新推荐文章于 2024-08-17 23:59:05 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)