派生类调用基类方法时会自动转成基类类型

class A
{
    public:
    int a;
    void showthis()
    {
        printf("from A,this:%p\n", this);
    }
};
class B
{
    public:
    int b;
    void infothis()
    {
        printf("from B,this:%p\n", this);
    }
};
class C:public A, public B
{
    public:
    C(){
        printf("from C:this:%p\n", this);    
    }
};

int main()
{
    C c;
    c.showthis();
    c.infothis();
    
    return 0;
}

编译运行,输出:

from C:this:0x7ffff4321a80
from A,this:0x7ffff4321a80
from B,this:0x7ffff4321a84

类型转换可能伴随着this地址的变化,派生类的this和基类的this所指有偏差,要转成基类this指针.

猜你喜欢

转载自www.cnblogs.com/xiang-yin/p/12076262.html