标签:result name 源程序 str add res names 程序 class
1. 开闭原则
#include<iostream>
using namespace std;
//设计模式,开闭原则:增加新功能是通过增加代码来实现,而不是修改源程序
//设计一个计算器,实现加减乘除
class Calulate
{
public:
virtual int getResult() = 0;
};
class add: public Calulate
{
public:
add(int x, int y):m_a(x), m_b(y)
{}
virtual int getResult()
{
return m_a + m_b;
}
private:
int m_a;
int m_b;
};
class subtra: public Calulate
{
public:
subtra(int x, int y):m_a(x), m_b(y)
{}
virtual int getResult()
{
return m_a - m_b;
}
private:
int m_a;
int m_b;
};
class multi: public Calulate
{
public:
multi(int x, int y):m_a(x), m_b(y)
{}
virtual int getResult()
{
return m_a * m_b;
}
private:
int m_a;
int m_b;
};
class divi: public Calulate
{
public:
divi(int x, int y):m_a(x), m_b(y)
{}
virtual int getResult()
{
if (m_b)
{
return m_a / m_b;
}
else
return -1;
}
private:
int m_a;
int m_b;
};
int main()
{
Calulate *m_cal = new multi(5, 6);
cout << m_cal->getResult() << endl;
delete m_cal;
system("pause");
return 0;
}
标签:result name 源程序 str add res names 程序 class
原文地址:https://www.cnblogs.com/mengjuanjuan/p/10562056.html