【C++ Virtual 有啥用啊?】

1.应用于多态中

代码示例如下

复制代码
#include <iostream>
using namespace std;

class Animal
{
public:
	Animal(){}
	~Animal(){}
	void shout()
	{
		cout << "Animal is shout!" << endl;
	}
};

class Dog:public Animal
{
public:
	Dog():Animal(){}
	~Dog(){}
	void shout()
	{
		cout << "Dog is shout!" << endl;
	}
};

class Cat:public Animal
{
public:
	Cat():Animal(){}
	~Cat(){}
	void shout()
	{
		cout << "Cat is shout!" << endl;
	}
};
int main()
{
   Animal *dog = new Dog();
   Animal *cat = new Cat();
   dog->shout();
   cat->shout();
   return 0;
}

以下是其输出

复制代码
Animal is shout!
Animal is shout!

解释 :子类对象,使用父类指针进行声明,相当于'向上转换',转换后的指针拥有且仅拥有父类属性方法!!!

虽然父类和子类都有各自的shout方法,但是如果这么写,他们一点关系都没有!!!这等同于,父类中拥有方法0,子类1中扩展出了方法1,子类2中扩展出了方法2。

所以,你想说,我不是在子类中重写了shout方法吗?虽然'向上转换了',不应该用我重写后方法吗?抱歉,父类中的shout方法很直男!!!想让他脑瓜儿灵活点,重写请使用virtual
请不要混淆重载(同一个类中)和重写(用于继承关系中)
这里还说了另外两种用法:纯虚函数(抽象类)和虚拟继承(解决菱形继承问题)

修改后的代码示例如下:

复制代码
#include <iostream>
using namespace std;

class Animal
{
public:
	Animal(){}
	~Animal(){}
	virtual void shout()
	{
		cout << "Animal is shout!" << endl;
	}
};

class Dog:public Animal
{
public:
	Dog():Animal(){}
	~Dog(){}
	void shout()
	{
		cout << "Dog is shout!" << endl;
	}
};

class Cat:public Animal
{
public:
	Cat():Animal(){}
	~Cat(){}
	void shout()
	{
		cout << "Cat is shout!" << endl;
	}
};
int main()
{
   Animal *dog = new Dog();
   Animal *cat = new Cat();
   dog->shout();
   cat->shout();
   return 0;
}

输出如下

复制代码
Dog is shout!
Cat is shout!

所以想让父类指针聪明些,重写 请使用virtual。(在父类中声明virtual即可)

virtual隔代都有效

比如现在孙子类狼青继承自Dog,向上转换后的爷类指针和父类指针,也会按照狼青那样叫。

代码示例如下

复制代码
#include <iostream>
using namespace std;

class Animal
{
public:
	Animal(){}
	~Animal(){}
	virtual void shout()
	{
		cout << "Animal is shout!" << endl;
	}
};

class Dog:public Animal
{
public:
	Dog():Animal(){}
	~Dog(){}
	void shout()
	{
		cout << "Dog is shout!" << endl;
	}
};

class Cat:public Animal
{
public:
	Cat():Animal(){}
	~Cat(){}
	void shout()
	{
		cout << "Cat is shout!" << endl;
	}
};
class Langqing:public Dog
{
public:
	Langqing():Dog(){}
	~Langqing(){}
	void shout()
	{
		cout << "Langqing is shout!" << endl;
	}
};
int main()
{
   Animal *dog = new Dog();
   Animal *cat = new Cat();
   dog->shout();
   cat->shout();
   Animal *lq1 = new Langqing();
   lq1->shout();
   Dog *lq2 = new Langqing();
   lq2->shout();
   return 0;
}

输出如下

复制代码
Dog is shout!
Cat is shout!
Langqing is shout!
Langqing is shout!
相关推荐
翻滚丷大头鱼20 分钟前
Java 集合Collection—List
java·开发语言
小欣加油21 分钟前
leetcode 面试题01.02判定是否互为字符重排
数据结构·c++·算法·leetcode·职场和发展
王璐WL32 分钟前
【c++】c++第一课:命名空间
数据结构·c++·算法
aramae39 分钟前
C++ -- 模板
开发语言·c++·笔记·其他
胡耀超40 分钟前
4、Python面向对象编程与模块化设计
开发语言·python·ai·大模型·conda·anaconda
索迪迈科技1 小时前
java后端工程师进修ing(研一版 || day40)
java·开发语言·学习·算法
Zz_waiting.2 小时前
Javaweb - 14.6 - Vue3 数据交互 Axios
开发语言·前端·javascript·vue·axios
萌新小码农‍2 小时前
Java分页 Element—UI
java·开发语言·ui
Tiger_shl2 小时前
【.Net技术栈梳理】03-核心框架与运行时(异常处理)
开发语言·.net
再睡亿分钟!2 小时前
Spring MVC 的常用注解
java·开发语言·spring boot·spring