C++虚函数的一些问题(1)

class A
{
public:
	void func_A() { func_B(); }
	void func_B() { cout << "A:func_B" << endl; }
};

class B : public A
{
public:
	void func_B() { cout << "B:func_B" << endl; }
};
int main()
{
	B b;
	b.func_A();
	system("pause");
	return 0;
}

输出结果是:A:func_B

class A
{
public:
	void func_A() { func_B(); }
	virtual void func_B() { cout << "A:func_B" << endl; }
};

class B : public A
{
public:
	void func_B() { cout << "B:func_B" << endl; }
};
int main()
{
	B b;
	b.func_A();
	system("pause");
	return 0;
}

输出结果是:B:func_B


我的理解是,在类成员函数中的this指针,类型均是与该类相同,调用时this的值为调用对象的地址,但是这个对象不一定是该类类型,有可能是派生类类型。

上面的两个例子中,在classA的func_A里,this指针为A类型,通过b.func_A()派生类对象调用基类函数时,func_A中的this指针指向b,所以在func_A中,通过隐藏的this调用func_B的方式,满足最常见的虚函数动态多态性特征(基类指针指向派生类,调用同名函数)。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值