在 C++ 中获取类对象的地址?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6012190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 19:20:22  来源:igfitidea点击:

Get the address of class's object in C++?

c++memory-address

提问by ipkiss

Suppose I have a C++ class as follows:

假设我有一个 C++ 类,如下所示:

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;

如果我想知道 p2 的地址,那么我可以使用&p2. 但是我怎样才能得到 p2 存储的地址呢?因为 p2 不是指针,所以我不能只使用cout << p2;

回答by sje397

What's wrong with the following:

以下有什么问题:

cout << &p2;

As you say, p2is not a pointer. Conceptually it is a block of data stored somewhere in memory. &p2is the address of this block. When you do:

正如你所说,p2是不是一个指针。从概念上讲,它是存储在内存中某处的数据块。&p2是这个块的地址。当你这样做时:

Point p2 = p1;

...that data is copied to the block 'labelled' p1.

...该数据被复制到块 'labelled' p1

But how can I get the address that p2 stores?

但是我怎样才能得到 p2 存储的地址呢?

Unless you add a pointer member to the Pointdata structure, it doesn't store an address. As you said, it's not a pointer.

除非您向Point数据结构添加指针成员,否则它不会存储地址。正如你所说,它不是一个指针。

P.S. The hexstream operator might be useful too:

PS十六进制流运算符也可能有用:

cout << hex << &p2 << endl;

回答by hauron

By doing

通过做

Point p2 = p1;

you simply copy the values of p2 onto p1 (most likely). The memory is independent. If you did instead:

您只需将 p2 的值复制到 p1 上(最有可能)。内存是独立的。如果你这样做了:

Point* p2 = &p1;

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).

然后 p2 将是指向 p1 的指针(打印其值将为您提供内存块的开头,然后您可以尝试使用 sizeof 来获取块的大小)。