C++虚函数大总结

本文探讨了C++中虚拟函数的使用及其在类继承中的作用,包括实例化对象、调用虚函数的过程及结果分析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、虚函数需要实现才能调用,否则出现错误crashed

class A
{
public:
	void function(){printf("Hello World");}

};

class B
{
public:
	virtual void function(){printf("Hello World");}
};

int main(int argc, char* argv[])
{
	A* p1 = NULL;
	p1->function();

	B* p2 = NULL;
	p2->function();
	system("pause");
	return 0;

};

P1 能helloword

P2 crashed


2、基类虚函数,子类可以动态调用

class A
{
public:
	virtual void foo() { cout << "A::foo() is called" << endl;}
};

class B: public A
{
public:
	void foo() { cout << "B::foo() is called" << endl;}
};

int main()
{
	A * a = new B();
	a->foo(); 
	//testvirtual();
	system("pause");
}

结果:B类中的virtual 加不加结果都一样

输出结果:B::foo() is called

3、基类非虚函数,子类虚函数

class A
{
public:
	 void foo() { cout << "A::foo() is called" << endl;}
};

class B: public A
{
public:
	virtual void foo() { cout << "B::foo() is called" << endl;}
};

输出结果:
A::foo() is called



好了,先写这么多,以后在增加





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值