26~C++多态条件下的this指针

大家都知道,this指针指向了对象的起始地址
本节结合多态条件说明一个有关this指针的趣事!

#include <iostream>
using namespace std;
class A {
public:
	A (void) {
		cout << "A this " << this << endl;
	}

	virtual void fool(void)
	{
		cout << "A::fool " << endl;
	}
int m_a;
};

class B  {
public:
	B (void) {
		cout << "B this " << this << endl;
	}
	
	virtual void print(void)
	{
		cout << "B::print " << "this = " << this << endl;
	}
int m_b;
};
class C :public A, public B {
public:
	C (void)
	{
		cout << "C this " << this << endl;
	}
	virtual void print(void)
	{
		cout << "C::print " << "this = " << this << endl;
	}
int m_c;
};

int main(void){
C c;

A* pa  = &c;
B* pb = &c;
C* pc = &c;

cout << "pa = " << pa 
	<< " pb =" << pb 
	<< " pc= " << pc 
	<< endl;
/*调用成员函数print需要两个必备条件:1、成员函数指针 2、正确的this指针
条件1,成员函数指针通过虚表得到
条件2,pb是基类对象指针,pb->print()得到子类函数指针:编译器通过pb基类对象向下造型出一个子类this指针来匹配子类成员函数*/
pb->print();
pc->print();
return 0;
}

输出:
A this 0x7fff1e437e50
B this 0x7fff1e437e60
C this 0x7fff1e437e50
pa = 0x7fff1e437e50 pb =0x7fff1e437e60 pc= 0x7fff1e437e50
C::print this = 0x7fff1e437e50
C::print this = 0x7fff1e437e50

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值