C++:理解 "this" 指针

C++ : Understanding "this" Pointer

我想了解"this"指针。我认为 "this" 指针指的是 class 对象的值。 但是,在下面的代码中,我可以看到 "this" 指针的不同值:

#include <stdio.h>

class InterfaceA{
public:
    virtual void funa() = 0;
};

class InterfaceB{
public:
    virtual void funb() = 0;
};

void globala(InterfaceA* obj){
    printf("globalA: pointer: %p\n\r",obj);
}
void globalb(InterfaceB* obj){
    printf("globalB: pointer: %p\n\r",obj);
}
class concrete : public InterfaceA, public InterfaceB{
public:
    void funa(){
        printf("funa: pointer: %p\n\r",this);
        globala(this);
        globalb(this);
    }

    void funb(){
        printf("funb: pointer: %p\n\r",this);
        globala(this);
        globalb(this);
    }
};

int main(int argc, char *argv[])
{
    concrete ac;
    ac.funa();
    ac.funb();
    return 0;
}

该程序的输出为:

funa: pointer: 0x7ffff67261a0
globalA: pointer: 0x7ffff67261a0
globalB: pointer: 0x7ffff67261a8
funb: pointer: 0x7ffff67261a0
globalA: pointer: 0x7ffff67261a0
globalB: pointer: 0x7ffff67261a8

任何帮助理解这一点。

谢谢。

I thought that "this" pointer refers to the value of the class object.

正确。 this 始终指向调用成员函数的对象。

I could see different values of "this" pointer

哦,但是你没有打印 this(在 globalAglobalB 中)。您打印的 obj 甚至与 this.

的类型不同

thisconcrete* 类型。当您将它传递给接受类型 InterfaceB* 参数的函数时,指针隐式为 converted to the other type. The conversion is allowed because interfaceB is a base of concrete. The converted pointer will no longer point to this object, but a base class sub object. A sub object (base class instance or a member) may but might not have the same address as the main object. Sub objects of an object cannot share an address, so at most one sub object may have the same address as the main object - except in the case of empty base optimization.

this是一个指针,指向调用成员函数的对象。

this的类型取决于成员函数。

例如对于一个class X,如果成员函数是

1)const,则thisconst X*

类型

2) volatile,那么this就是volatile X*

否则就是X*