c++--对象this指针调整

派生类对象他是包含基类子对象的

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

但如果派生类对象同时继承多个基类,那么要注意,第一个基类子对象的开地址和派生类的开始地址相同,后续这些基类子类对象的开始地址和派生类对象的开始地址相差多少呢?那就得把前面那些基类子对象内存大小加上。

#include <iostream>

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

};

class B
{
public:
    int b;
    B() {
        printf("B::B()的this指针是:%p!\n", this);
    }
    ~B() {};
    void funcB() {
        printf("B::funcB()的this指针是:%p!\n", this);
    }

};

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


using namespace std;
//类对象所占用的空间大小
int main()
{

    cout << sizeof(A) << endl;
    cout << sizeof(B) << endl;
    cout << sizeof(C) << endl;
    C myc;
    myc.funcA();
    myc.funcB();
    myc.funcC();
    return 1;
}

 

posted @ 2022-04-07 15:52  伊红美兰  阅读(37)  评论(0编辑  收藏  举报