C++基础之关键字——virtual详解

修饰父类中的普通函数

被修饰的函数称为虚函数, 是C++中多态的一种实现(多说一句,多态分编译时多态-通过重载实现和运行时多态-通过虚函数实现)。 也就是说用父类的指针或者引用指向其派生类的对象,当使用指针或引用调用函数的时候会根据具体的对象类型调用对应对象的函数(需要两个条件:父类的函数用virtual修饰和子类要重写父类的函数)。下面用一个例子来说明:

cpp 复制代码
#include <iostream>

class father {
public:
	void func1() {std::cout << "this is father func1" << std::endl;}
	virtual void func2() {std::cout << "this is father func2" << std::endl;
}

class son:public father {
public:
	void func1() {std::cout << "this is son func1" << std::endl;}
	void func2() {std::cout << "this is son func2" << std::endl;
}

int main() {
	father *f1 = new son();
	f1.func1();
	f1.func2();
	return 0;
}

output:

cpp 复制代码
this is father func1
this is son func2

通过上面的例子可以看出,使用virtual修饰的函数会根据实际对象的类型来调用,没有使用virtual修饰的根据指针的类型来调用。虚函数最关键的特点是"动态联编",它可以在运行时判断指针指向的对象,并自动调用相应的函数。

Reference

相关推荐
fanruitian21 小时前
Springboot项目父子工程
java·数据库·spring boot
小肖爱笑不爱笑21 小时前
SpringBoot Web
java·http协议·分层解耦·web后端
柒.梧.21 小时前
Spring核心知识全解析:从入门实战到进阶
java·后端·spring
乌日尼乐1 天前
【Java基础整理】Java字符串处理,String、StringBuffer、StringBuilder
java·后端
全栈独立开发者1 天前
点餐系统装上了“DeepSeek大脑”:基于 Spring AI + PgVector 的 RAG 落地指南
java·人工智能·spring
dmonstererer1 天前
【k8s设置污点/容忍】
java·容器·kubernetes
super_lzb1 天前
mybatis拦截器ParameterHandler详解
java·数据库·spring boot·spring·mybatis
程序之巅1 天前
VS code 远程python代码debug
android·java·python
liulilittle1 天前
XDP VNP虚拟以太网关(章节:一)
linux·服务器·开发语言·网络·c++·通信·xdp
我是Superman丶1 天前
【异常】Spring Ai Alibaba 流式输出卡住无响应的问题
java·后端·spring