"this"指针如何指向不同的对象?

Avi*_*mar 1 c++ pointers this this-pointer

假设我有一个班级:

class test {
public:
   void print();
private:
   int x;
};

void test::print()  
{  
    cout<< this->x;  
}
Run Code Online (Sandbox Code Playgroud)

我有这些变量定义:

test object1;
test object2;
Run Code Online (Sandbox Code Playgroud)

当我打电话object1.print() this时碰巧存储地址,object1所以我xobject1打印得到,当我打电话object2.print() this时,恰好是存储地址,object2xobject2打印到.怎么会发生?

sha*_*oth 6

每个非静态成员函数都有一个隐式隐藏的"当前对象"参数,该参数作为this指针向您公开.

所以你可以这么认为

test::print();
Run Code Online (Sandbox Code Playgroud)

有一些

test_print( test* this );
Run Code Online (Sandbox Code Playgroud)

全局功能等等你写的时候

objectX.print();
Run Code Online (Sandbox Code Playgroud)

在您的代码中,编译器插入一个调用

test_print(&objectX);
Run Code Online (Sandbox Code Playgroud)

这样,成员函数就知道"当前"对象的地址.