如何在C ++类中通过`this`引用获取对象的内存地址]

问题描述 投票:0回答:1
如何使用C ++中的this引用获取类内部对象的内存地址。

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

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

我想使用this参考。类似于:

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

但是以上代码给出了一个错误。是否可以用C ++。

如何使用C ++中的此引用获取类内对象的内存地址。我可以使用以下命令获取类外部对象的内存地址:Obj obj(); cout <

void Obj::method() { cout << &*this << " or " << this << endl; }
我可以通过使用以下方法获取类外部对象的内存地址:以下:

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

不是类型Obj的对象的内存地址。这是返回Obj的函数的内存地址。


void Obj::method() { cout << &this << endl; }
您不能使用this的地址。您也不应该这样,因为您想要的是对象的地址。 this已经是此对象的指针,因此请不要使用addressof运算符。
c++ reference this
1个回答
0
投票
void Obj::method() { cout << &*this << " or " << this << endl; }

0
投票
我可以通过使用以下方法获取类外部对象的内存地址:以下:
© www.soinside.com 2019 - 2024. All rights reserved.