[英]How to get the memory address of an object with `this` reference inside the class in C++
How can I get the memory address of an object inside a class with this
reference in C++.如何在 C++ 中使用this
引用获取类内对象的内存地址。
I can get the memory address of an object outside the class by using the following:我可以使用以下方法获取类外对象的内存地址:
Obj obj();
cout << &obj << endl;
I want to do this with this
reference.我想用this
参考来做到这this
。 Something like:就像是:
void Obj::method()
{
cout << &this << endl;
}
But the above code gives an error.但是上面的代码给出了一个错误。 Is it possible in C++.在 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;
That is not memory address of an object of type Obj
.这不是Obj
类型的对象的内存地址。 That is the memory address of a function that returns Obj
.那是返回Obj
的函数的内存地址。 A function pointer won't be printed by a stream though, and is converted to a bool instead, so you'll always see 1.函数指针不会被流打印,而是被转换为 bool,所以你总是会看到 1。
void Obj::method() { cout << &this << endl; }
You cannot take the address of this
.你不能取this
的地址。 You shouldn't either because what you want is the address of the object.你也不应该因为你想要的是对象的地址。 this
is already a pointer to this object, so simply don't use the addressof operator. this
已经是一个指向这个对象的指针,所以不要使用 addressof 操作符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.