对象-this指针

 

#include <iostream>
using namespace std;

class A
{
  public:
    int a;
    A()
    {
        printf("A::A()的this指针是%p\n", this);
    }

    void funA()
    {
        printf("A::funA()的this指针是%p\n", this);
    }
};

class B
{
  public:
    int c;
    B()
    {
        printf("B::B()的this指针是%p\n", this);
    }

    void funB()
    {
        printf("B::funB()的this指针是%p\n", this);
    }
};

class C : public A, public B
{
  public:
    int c;
    C()
    {
        printf("C::C()的this指针是%p\n", this);
    }

    void funC()
    {
        printf("C::funC()的this指针是%p\n", this);
    }
};

int main(int, char**) 
{
    //this指针调整,多重继承
    cout << sizeof(A) << endl;
    cout << sizeof(B) << endl;
    cout << sizeof(C) << endl;

    C myc;//生成myc时,会构造C类的对象,类C继承A和B,在执行C的构造函数时,也会执行A和B的构造函数
    myc.funA();
    myc.funB();
    myc.funC();

    //编译结果
    // 4
    // 4
    // 12
    // A::A()的this指针是0x7fff6ada1a7c
    // B::B()的this指针是0x7fff6ada1a80
    // C::C()的this指针是0x7fff6ada1a7c
    // A::funA()的this指针是0x7fff6ada1a7c
    // B::funB()的this指针是0x7fff6ada1a80
    // C::funC()的this指针是0x7fff6ada1a7c

    // ==>

    // 派生类对象包含基类子对象: myc是包含A类子对象,也包含B类子对象的.
    // 如果派生类只从一个基类继承的话,这个派生类对象的地址和基类对象的地址相同
    // 但如果一个派生类对象继承了多个基类:
       // 第一个基类子对象的开始地址和派生类对象的开始地址相同.
       // 而后续这些基类子对象的开始地址和派生类对象的开始地址相差多少呢?
          // 前面基类子对象所占用的内存空间

    return 1;

}

在C中添加一个B中相同的成员函数.
 

#include <iostream>
using namespace std;

class A
{
  public:
    int a;
    A()
    {
        printf("A::A()的this指针是%p\n", this);
    }

    void funA()
    {
        printf("A::funA()的this指针是%p\n", this);
    }
};

class B
{
  public:
    int c;
    B()
    {
        printf("B::B()的this指针是%p\n", this);
    }

    void funB()
    {
        printf("B::funB()的this指针是%p\n", this);
    }
};

class C : public A, public B
{
  public:
    int c;
    C()
    {
        printf("C::C()的this指针是%p\n", this);
    }

    void funC()
    {
        printf("C::funC()的this指针是%p\n", this);
    }

    void funB()
    {
        printf("C::funB()的this指针是%p\n", this);
    }
};

int main(int, char**) 
{
    //this指针调整,多重继承
    cout << sizeof(A) << endl;
    cout << sizeof(B) << endl;
    cout << sizeof(C) << endl;

    C myc;//生成myc时,会构造C类的对象,类C继承A和B,在执行C的构造函数时,也会执行A和B的构造函数
    myc.funA();
    myc.funB(); //已经被子类c覆盖了
    myc.B::funB();
    myc.funC();

    //编译结果
    // 4
    // 4
    // 12
    // A::A()的this指针是0x7ffc217e244c
    // B::B()的this指针是0x7ffc217e2450
    // C::C()的this指针是0x7ffc217e244c
    // A::funA()的this指针是0x7ffc217e244c
    // C::funB()的this指针是0x7ffc217e244c
    // B::funB()的this指针是0x7ffc217e2450
    // C::funC()的this指针是0x7ffc217e244c

    // ==>

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

    return 1;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值