实现:多态计算机类

这里一共写了两种实现,普通的写法,还有一种的多态的写法,进行比较

自己感觉多大的区别其实就是:解耦性

两种方法都没有错,主要在后期的维护中,普通写法修改一个地方,可能就会导致牵一发而动全身的后果,而多态的写法,体现了解耦的思想,更方法单一进行修改

多态写法:

代码如下

#include<iostream>
#include<string>

using namespace std;

class Dt_jsj {
public:

	virtual int to_js() {
		return 0;
	} //定义了一个虚函数,那么相应的也会生成虚拟指针和虚拟表

public:
	int a;
	int b;
};

class Add_jsj:public Dt_jsj{
public:
	int to_js() {
		return a + b;
	}
};


class Sub_jsj :public Dt_jsj{
public:
	int to_js() {
		return a - b;
	}
};


void test01() {
	Dt_jsj  * jsj = new Add_jsj; //生成一个Dt_jsj的指针 指向new出来的内存地址,相当于引用 Dt_jsj & jsj    
	jsj->a = 100;
	jsj->b = 100;
	cout << jsj->to_js() << endl;
}


int main() {
	test01();
	system("pause");
	return 0;
}

普通写法:

代码如下

#include<iostream>
#include<string>

using namespace std;

//普通计算机类的实现
class Common_jsj {
public:
	Common_jsj(int a, int b) {
		this->a = a;
		this->b = b;
	}

	//void to_js(string fuh) { //发现switch对string不支持那就只能换成if语句了
	//	switch (fuh) {
	//	case '+':
	//		return this->a + this->b;
	//	case '-':
	//		return this->a - this->b;
	//	case '*':
	//		return this->a * this->b;
	//	}
	//}
	int to_js(string fuh) {
		if (fuh == "+") {
			return this->a + this->b;
		}
		else if (fuh == "-") {
			return this->a - this->b;
		}
		else if (fuh == "*") {
			return this->a * this->b;
		}
	}

public:
	int a;
	int b;

};

void test01() {
	Common_jsj j1(100, 100);
	cout << j1.to_js("+") << endl;
}
int main() {
	test01();
	system("pause");
	return 0;
}
原文地址:https://www.cnblogs.com/zpchcbd/p/11871029.html