【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!
相关推荐
No0d1es5 分钟前
2025年第十六届蓝桥杯青少组省赛 C++编程 中级组真题
c++·青少年编程·蓝桥杯·省赛
千禧皓月14 分钟前
【C++】基于C++的RPC分布式网络通信框架(二)
c++·分布式·rpc
南汐汐月34 分钟前
重生归来,我要成功 Python 高手--day33 决策树
开发语言·python·决策树
AA陈超40 分钟前
虚幻引擎5 GAS开发俯视角RPG游戏 P07-08 点击移动
c++·游戏·ue5·游戏引擎·虚幻
星释1 小时前
Rust 练习册 :Proverb与字符串处理
开发语言·后端·rust
·白小白1 小时前
力扣(LeetCode) ——209. 长度最小的子数组(C++)
c++·算法·leetcode
工会主席-阿冰1 小时前
数据索引是无序时,直接用这个数据去画图的话,显示的图是错误的
开发语言·python·数据挖掘
ohnoooo91 小时前
251106 算法
数据结构·c++·算法
麦麦鸡腿堡1 小时前
Java_TreeSet与TreeMap源码解读
java·开发语言
gladiator+2 小时前
Java中的设计模式------策略设计模式
java·开发语言·设计模式