如何在 C++ 中的 class 中获取带有 `this` 引用的对象的内存地址

How to get the memory address of an object with `this` reference inside the class in C++

如何在 C++ 中使用 this 引用获取 class 中对象的内存地址。

我可以使用以下方法获取 class 之外的对象的内存地址:

Obj obj();
cout << &obj << endl;

我想用 this 参考来做到这一点。类似于:

void Obj::method()
{
    cout << &this << endl;
}

但是上面的代码报错了。在C++中可以吗

void Obj::method()
{
    cout << &*this << " or " << this << endl;
}

I can get the memory address of an object outside the class by using the following:

Obj obj();
cout << &obj << endl;

这不是 Obj 类型对象的内存地址。即returnsObj函数的内存地址。函数指针不会被流打印出来,而是转换为布尔值,所以你总是会看到 1.


void Obj::method()
{
    cout << &this << endl;
}

您不能使用 this 的地址。你也不应该因为你想要的是对象的地址。 this 已经是指向该对象的指针,所以不要使用 addressof 运算符。