0
点赞
收藏
分享

微信扫一扫

从0搭建Vue3组件库(四): 如何开发一个组件

天天天蓝loveyou 2023-05-04 阅读 51

多态的基本语法

多态是C++面向对象三大特性之一

 案例:

#include<iostream>
using namespace std;
class animal
{
public:
	void speak()
	{
		cout << "animal is speaking" << endl;
	}
	/*改成下面就可以变成小猫说话了,即多态
	virtual void spaek()//虚函数
	{
		cout << "animal is speaking" << endl;
	}
	*/
};
class cat :public animal
{
public:
	void speak()//virtual可写可不写
	{
		cout << "cat is speaking" << endl;
	}
};
void dospeak(animal& animal)//animal &animal=cat;
{//C++中允许父子间的类型转换(无需强制转换)
 //父类的指针或引用可以直接指向子类对象

	animal.speak();

//不管传入什么都会走animal里的speak函数
//因为它是地址早绑定   在编译阶段就确定了函数地址
//如果想让传进来的动物说话  就要让地址晚绑定
}
int main()
{
	cat cat;
	dospeak(cat);
	system("pause");
	return 0;
}

输出:

 但是这里dospeak传入的是cat,我们是想要cat说话

原理剖析

不管是几级、什么类型,指针都占4个字节

案例1-计算器类

对多态的理解:同样是购票,不同的对象有不同的结果。

普通写法

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

class calculator
{
public:
	int getresult(string op)
	{
		if (op == "+") return m_num1 + m_num2;
		if (op == "-") return m_num1 - m_num2;
		if (op == "*") return m_num1 * m_num2;
	}
	int m_num1;
	int m_num2;
};
void test01()
{
	calculator c;
	c.m_num1 = 10;
	c.m_num2 = 10;
	cout << c.getresult("+") << endl << c.getresult("-") << endl << c.getresult("*") << endl;
}
int main()
{
	test01();
	system("pause");
	return 0;
}

弊端:如果要新增操作  除法  ,就需要修改   getresult  里面的代码。

在真实开发中提倡开闭原则:对扩展进行开放,对修改进行关闭

多态写法

#include<iostream>
#include<string>
using namespace std;
//利用多态实现计算器

class calculator//先实现计算器抽象类
{
public:
	virtual int getresult()
	{
		return 0;
	}
	int m_num1;
	int m_num2;
};
class addcalculator :public calculator
{
public:
	virtual int getresult()
	{
		return m_num1 + m_num2;
	}
};

class subcalculator :public calculator
{
public:
	virtual int getresult()
	{
		return m_num1 - m_num2;
	}
};

class mulcalculator :public calculator
{
public:
	virtual int getresult()
	{
		return m_num1 * m_num2;
	}
};
void test02()
{//多态使用条件
//父类指针或引用指向子类对象

	//加法运算
	calculator* abc = new addcalculator;
	abc->m_num1 = 10;
	abc->m_num2 = 10;
	cout << abc->getresult() << endl;
	
	delete abc;//用完后记得销毁

	//减法运算
	abc = new subcalculator;
	//指针本身是父类指针,释放的是堆区的数据,但是指针本身的类型并没有改变
	abc->m_num1 = 100;
	abc->m_num2 = 120;
	cout << abc->getresult() << endl;
	delete abc;

	//乘法运算
	abc = new mulcalculator;
	//指针本身是父类指针,释放的是堆区的数据,但是指针本身的类型并没有改变
	abc->m_num1 = 10;
	abc->m_num2 = 12;
	cout << abc->getresult() << endl;
}
int main()
{
	test02();
	system("pause");
	return 0;
}

便于修改,可读性强。前后期便于扩展和维护。

C++开发提倡利用多态设计程序架构,因为多态优点很多

纯虚函数和抽象类

举报

相关推荐

0 条评论