在C中获取类对象的地址?
假设我有一个如下的C++类:
class Point {
// implementing some operations
}
那么:
Point p1;
Point p2 = p1;
如果我想知道p2的地址,那么我可以使用&p2
。但是我怎样才能得到p2存储的地址呢?因为 p2 不是指针,所以我不能只使用 cout << p2;
Suppose I have a C++ class as follows:
class Point {
// implementing some operations
}
Then:
Point p1;
Point p2 = p1;
If I want to know the address of p2, then I can use &p2
. But how can I get the address that p2 stores? Because p2 is not a pointer, so I cannot just use cout << p2;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
以下有什么问题:
正如你所说,
p2
不是一个指针。从概念上讲,它是存储在内存中某处的数据块。&p2
是该块的地址。当您执行以下操作时:...该数据将复制到“标记为”
p1
的块。除非您向
Point
数据结构添加指针成员,否则它不会存储地址。正如你所说,它不是一个指针。PS hex 流运算符也可能很有用:
What's wrong with the following:
As you say,
p2
is not a pointer. Conceptually it is a block of data stored somewhere in memory.&p2
is the address of this block. When you do:...that data is copied to the block 'labelled'
p1
.Unless you add a pointer member to the
Point
data structure, it doesn't store an address. As you said, it's not a pointer.P.S. The hex stream operator might be useful too:
通过这样做,
您只需将 p2 的值复制到 p1 上(很可能)。记忆是独立的。
如果你这样做了:
那么 p2 将是指向 p1 的指针(打印它的值将为你提供内存块的开始,然后你可以尝试使用 sizeof 来获取块的大小)。
By doing
you simply copy the values of p2 onto p1 (most likely). The memory is independent.
If you did instead:
then p2 will be a pointer onto p1 (printing its value will give you the begining of the memory block, you could then try the sizeof to get the size of the block).
接受的答案建议使用运算符
&
来获取对象的地址。从 C++11 开始,如果对象类定义/重载运算符
&
,则此解决方案不起作用。为了获取对象的地址,从 C++11 开始,应使用模板函数
std::addressof()
。http://www.cplusplus.com/reference/memory/addressof/
The accepted answer proposes the use of operator
&
to obtain the address of an object.As of C++11, this solution does not work if the object class defines/overloads operator
&
.In order to get the address of an object, from C++11, the template function
std::addressof()
should be used instead.http://www.cplusplus.com/reference/memory/addressof/