多态案例:实现计算机类

2021-02-22 11:04:46 浏览数 (1)

代码语言:javascript复制
#include<iostream>
using namespace std;
//多态实现计算器
class Culculator {
public:
	int num1;
	int num2;
	char ch;
	virtual int GetResult(char ch,int num1,int num2) = 0;
};
class Add:public Culculator{
public:
	int GetResult(char ch,int num1,int num2) {
		this->num1 = num1;
		this->num2 = num2;
		if (ch == ' ')
		return (num1   num2);
	}
};
class Minus :public Culculator {
public:
	int GetResult(char ch,int num1,int num2)
	{
		this->num1 = num1;
		this->num2 = num2;
		if (ch == '-')
			return (num1 - num2);
	}
};
class Mul :public Culculator {
public:
	int GetResult(char ch, int num1, int num2) {
		this->num1 = num1;
		this->num2 = num2;
		if (ch == '*')
			return (num1 *num2);
	}
};
class Div :public Culculator {
public:
	int GetResult(char ch,int num1,int num2) {
		this->num1 = num1;
		this->num2 = num2;
		if (ch == '/')
			return (num1/num2);
	}
};
void ReturnResult(Culculator* cul) 
{
	int result=cul->GetResult('*',10,5);
	cout << "结果为" << result << endl;
	delete cul;
}
int main()
{
	ReturnResult(new Mul);
	system("pause");
	return 0;
}

0 人点赞