3.this指针: :多重继承

直接进入例子讲解

#include<iostream>
using namespace std;
​
class A
{
public:
    int a;
    A()
    {
        cout <<"A::A()的this指针是:" << this << endl;
    }
    void funca()
    {
        cout << "A::funca()的this指针是:" << this << endl;
    }
};
​
class B
{
public:
    int b;
    B()
    {
        cout << "B::B()的this指针是:" << this << endl;
    }
    void funcb()
    {
        cout << "B::funcb()的this指针是:" << this << endl;
    }
};
​
class C : public A, public B
{
public:
    int c;
    C()
    {
        cout << "C::C()的this指针是:" << this << endl;
    }
    void funcc()
    {
        cout << "C::funcc()的this指针是:" << this << endl;
    }
};
​
int main()
{
    cout << sizeof(A) << endl;
    cout << sizeof(B) << endl;
    cout << sizeof(C) << endl;
​
    C myc;
    myc.funca();
    myc.funcb();
    myc.funcc();
​
    return 0;
}

派生类对象 它是包含基类子对象的。

如果派生类只从一个基类继承的话,那么这个派生类对象的地址和基类子对象的地址相同。

但如果派生类对象同时继承多个基类,那么大家就要注意。

第一个基类子对象的开始地址和派生类对象的开始地址相同。

后续这些基类子对象的开始地址和派生类对象的开始地址相差多少呢?那就得把前边那些基类子对象所占用的内存空间干掉。

示意图:

#include<iostream>
using namespace std;
​
class A
{
public:
    int a;
    A()
    {
        cout <<"A::A()的this指针是:" << this << endl;
    }
    void funca()
    {
        cout << "A::funca()的this指针是:" << this << endl;
    }
};
​
class B
{
public:
    int b;
    B()
    {
        cout << "B::B()的this指针是:" << this << endl;
    }
    void funcb()
    {
        cout << "B::funcb()的this指针是:" << this << endl;
    }
};
​
class C : public A, public B
{
public:
    int c;
    C()
    {
        cout << "C::C()的this指针是:" << this << endl;
    }
    void funcc()
    {
        cout << "C::funcc()的this指针是:" << this << endl;
    }
​
    void funcb()
    {
        cout << "C::funcb()的this指针是:" << this << endl;
    }
};
​
int main()
{
    cout << sizeof(A) << endl;
    cout << sizeof(B) << endl;
    cout << sizeof(C) << endl;
​
    C myc;
    myc.funca();
    myc.funcb();
    myc.B::funcb();
    myc.funcc();
​
    return 0;
}

总结:你调用哪个子类的成员函数,这个this指针就会被编译器自动调整到对象内存布局中对应的子类对象的起始地址那去。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值