c++多态写法和普通写法的优劣对比(借用一个计算器类的实际案例来说明)

先说结论:相比于普通写法,我们更推荐多态写法。

案例:一个计算器类,实现加减乘操作。

1.普通写法

#include<iostream>
#include<string>
using namespace std;
class calculate {
	int m_a;
	int m_b;
public:
	calculate(int a, int b) {
		m_a = a;
		m_b = b;
	}
	int function_calculate(string str) {
		if (str == "+")
			return m_a + m_b;
		if (str == "-")
			return m_a - m_b;
		if (str == "*")
			return m_a + m_b;
		else
			cout << "error" << endl;
	}
};
void test01() {
	calculate c(100, 200);
	cout<<c.function_calculate("+");
}
int main() {
	test01();
}

2.多态写法

#include<iostream>
#include<string>
using namespace std;

class abstract_calculate {
public:
	virtual int function() { return 0; }
	int m_a;
	int m_b;
};

class add_calculate:public abstract_calculate{
public:
	int function() {
		return m_a + m_b;
	}
};

class sub_calculate :public abstract_calculate {
public:
	int function() {
		return m_a - m_b;
	}
};

class mul_calculate :public abstract_calculate {
public:
	int function() {
		return m_a * m_b;
	}
};
//通过父类指针指向子类的方法
void test01() {

	abstract_calculate* a = new add_calculate;
	a->m_a = 100;
	a->m_b = 200;
	cout<<a->function(); 
    delete a;
}

int main() {
	test01();
}

 概述:通过下面那张图不难发现,再在实现相同的功能时,动态写法的代码量更多,那为什么我们还要推广使用多态写法呢?

 

多态的优点:

  • 代码组织结构清晰
  • 可读性强,逻辑层次鲜明,代码像诗一样优美。
  • 利于前期和后期的扩展以及维护,快速定位。

在实际开发中,我们提倡开闭原则,即对扩展进行开发,对修改进行关闭。

就拿上面那个例子来说,我们普通写法在后期维护(就比如某个功能出错了)的时候还得去计算器类里一行一行读代码找到错误的那行,多态写法则直接找到相应的类就行,比如加法错了我就找加法那个类,其他的类我就不看了,这样就能实现快速定位,尤其是在一个大工程的时候,这样写很必要。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ad_m1n

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值