【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!
相关推荐
Layflok5 分钟前
《黑马笔记》 --- C++ 提高编程
开发语言·c++·stl
西红柿煎蛋14 分钟前
C++_stdmutex和stdatomic
c++
上单带刀不带妹25 分钟前
ES6中import与export的用法详解
开发语言·javascript·es6·import·export
西红柿煎蛋26 分钟前
C++11 Lambda表达式的本质是什么?它的捕获列表 ([]) 是如何工作的?
c++
工程师00730 分钟前
C#接口的定义与使用
开发语言·c#·接口
sali-tec30 分钟前
C# 基于halcon的视觉工作流-章27-带色中线
开发语言·人工智能·算法·计算机视觉·c#
范特西_34 分钟前
字典树/前缀树
c++·算法
编的过程1 小时前
vk框架或者普通函数封装的一些函数可以拿取使用【会持续更新】
开发语言·前端·javascript
sheepwjl1 小时前
《嵌入式C语言笔记(十七):进制转换、结构体与位运算精要》
linux·c语言·开发语言·笔记·算法
源代码•宸1 小时前
深入浅出设计模式——创建型模式之单例模式 Singleton
开发语言·c++·经验分享·单例模式·设计模式