- 普通类实现计算器
#include<iostream>
using namespace std;
#include <string>
//普通类写法
class Calculator
{
public:
int getResult(string oper)
{
if (oper == "+")
{
return m_num1 + m_num2;
}
else if(oper == "-")
{
return m_num1 - m_num2;
}
else if (oper == "*")
{
return m_num1 * m_num2;
}
else if (oper == "/")
{
return m_num1 / m_num2;
}
}
int m_num1;
int m_num2;
};
void test01()
{
//创建计算器对象
Calculator c;
c.m_num1 = 20;
c.m_num2 = 10;
cout << c.m_num1 << " + " << c.m_num2 << " = " << c.getResult("+") << endl;
cout << c.m_num1 << " - " << c.m_num2 << " = " << c.getResult("-") << endl;
cout << c.m_num1 << " * " << c.m_num2 << " = " << c.getResult("*") << endl;
cout << c.m_num1 << " / " << c.m_num2 << " = " << c.getResult("/") << endl;
}
int main() {
test01();
system("pause");
return 0;
}
如果要增加功能需要修改源码
- 多态
#include<iostream>
using namespace std;
#include <string>
//多态实现计算器
//计算器的抽象类
class AbstractCalculator
{
public:
virtual int getResult()
{
return 0;
}
int m_num1;
int m_num2;
};
//加法计算机器类
class AddCalculator:public AbstractCalculator
{
int getResult()
{
return m_num1 + m_num2;
}
};
//减法计算器类
class SupCalculator :public AbstractCalculator
{
int getResult()
{
return m_num1 - m_num2;
}
};
//乘法计算器类
class MulCalculator :public AbstractCalculator
{
int getResult()
{
return m_num1 * m_num2;
}
};
//除法计算器类
class DivCalculator :public AbstractCalculator
{
int getResult()
{
return m_num1 / m_num2;
}
};
void test02()
{
//多态使用条件:父类的指针或引用指向子类对象
//加法运算
AbstractCalculator* a = new AddCalculator;
a->m_num1 = 20;
a->m_num2 = 10;
cout << a->m_num1 << " + " << a->m_num2 << " = " <<a->getResult()<< endl;
delete a;
//减法运算
AbstractCalculator* b = new SupCalculator;
b->m_num1 = 20;
b->m_num2 = 10;
cout << b->m_num1 << " - " << b->m_num2 << " = " <<b->getResult()<< endl;
delete b;
//乘法运算
AbstractCalculator* c = new MulCalculator;
c->m_num1 = 20;
c->m_num2 = 10;
cout << c->m_num1 << " * " << c->m_num2 << " = " <<c->getResult()<< endl;
delete c;
//除法运算
AbstractCalculator* d = new DivCalculator;
d->m_num1 = 20;
d->m_num2 = 10;
cout << d->m_num1 << " / " << d->m_num2 << " = " <<d->getResult()<< endl;
delete d;
}
int main() {
test02();
system("pause");
return 0;
}