c++ - C++ 中的对象变量保存值,而不是对象引用

标签 c++ object reference

地址:http://www.horstmann.com/ccj2/ccjapp3.html , 在 A3.4 下。对象,提到了以下内容:

In C++, object variables hold values, not object references

你能澄清一下吗?而且,C++ 中是否只有 pointer 保存对象引用?

我们可以在这里说对象引用对象地址吗?

谢谢。

最佳答案

Can you clarify this point?

最好通过与例如比较来理解Java 或 C#:

MyClass a = new MyClass; // creates an instance.
MyClass b = a; // we still have one instance of MyClass in memory

与 C++ 相比:

MyClass a; // a *is* an instance of MyClass.
MyClass b = a; // we make a copy of a, now there are *two* instances of MyClass.

And, is it only the pointer in C++ that holds object references?

不,还有引用。

Can we say here that the object reference is the object address?

不,如果您指的是 A& 引用,那么它就是一个实现细节。您还可以实现具有引用语义的对象,就像在 C# 中一样工作。 pugixml库中的xml_node就是一个例子:

xml_node root = ...;
xml_node root2 = root; // doesn't copy the document
// root2 refers to the same object as root.

关于c++ - C++ 中的对象变量保存值,而不是对象引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4786211/

相关文章:

c++ - 将 C 代码合并到同一个 R 包中

powershell - 如何选择数组属性匹配变量的对象?

javascript - 按对象数组javascript中的多个键进行分组

c# - 如何将 "reference"分配给 C# 中的类字段?

c++ - 如何从现有的 vtkPolyData 复制折线的子集?

c++ - Wt C++ - 将 GET 值添加到 URL

c++ - 使用 dlsym 查找命名空间中符号的符号

php - 使用变量访问 PHP obj

通过引用传递的 java 函数原语

c++ - 右值的生命周期绑定(bind)到静态常量引用