如今想设计这样的一个计算器类,对提交上来的数据进行运算并返回结果:
- class calculation
- {
- public:
- calculation(int a, int b, string op) :_a(a), _b(b), _op(op)
- {};
- int getret()
- {
- if (_op == "+")
- return _a + _b;
- if (_op == "-")
- return _a - _b;
- if (_op == "*")
- return _a * _b;
- if (_op == "/")
- return _a / _b;
- }
- private:
- int _a;
- int _b;
- string _op;
- int _ret = 0;
- };
- void test()
- {
- calculation* ca1 = new calculation(1, 1, "+");
- cout << ca1->getret()<
- calculation* ca2 = new calculation(1, 1, "*");
- cout << ca2->getret()<
- }
- int main()
- {
- test();
- return 0;
- }
但是这段代码存在问题:如果想对该计算器类增添新的功能,比如说取余或者开方等等。那么就需要修改函数内的代码,这样就导致了一个问题:我们在修改代码的时候可能会出错,导致一系列后果,这就是所谓的高耦合。但是我们想到的是低耦合的代码。所以可以将不同的运算分别写在一个类中。这样就避免了上述问题:
- #include
- using namespace std;
- class getretClass
- {
- virtual int getret() = 0;
- };
- class Plus:public getretClass
- {
- public:
- Plus(int a, int b) :_a(a), _b(b) {};
- virtual int getret()
- {
- return _a + _b;
- }
- private:
- int _a;
- int _b;
- };
- class Minus:public getretClass
- {
- public:
- Minus(int a, int b) :_a(a), _b(b) {};
- virtual int getret()
- {
- return _a - _b;
- }
- private:
- int _a;
- int _b;
- };
- // 其他运算省略了
- void test()
- {
- Plus* plus = new Plus(1, 2);
- cout << plus->getret() << endl;
- Minus* minus = new Minus(2, 1);
- cout << minus->getret() << endl;
- }
- int main()
- {
- test();
- return 0;
- }
-
相关阅读:
python学习笔记(05)---(内置容器-列表)
git stash/git fetch/git rebase/git cherry pick/git reset
Qt/C++音视频开发71-指定mjpeg/h264格式采集本地摄像头/存储文件到mp4/设备推流/采集推流
知行合一的时候
C语言-找鞍点
SpringCloud进阶-消费者模块
paddlepaddle2.6,paddleorc2.8,cuda12,cudnn,nccl,python10环境
PowerQuery领域的经典之作“猴子书“中文版来啦!
【教程】部署apprtc服务中安装google-cloud-cli组件的问题及解决
消息队列与快递柜之间的奇妙关系
-
原文地址:https://blog.csdn.net/qq_64863535/article/details/136431568