C++ 是否可以返回对私有对象的引用并阻止更改
C++ Is it possible to return a reference to a private object and preventing change?
我需要返回对我编写的类的私有成员的引用。我是这样做的:
在MyClass2.h中,我有以下行
MyClass* getObj(){return &instance_myclass;}
我将确保我的代码不会更改 instance_myclass 的任何值。但只是为了确保,有没有办法只读地返回此引用,以便我无法更改其值?或者,根据定义,这是不可能的?
您当前返回的不是引用,而是指针。
要返回引用,请使用:
MyClass& getObj() { return instance_myclass; }
如果你想通过该引用防止修改,只需让它const
(当你使用它时,也使函数const
):
MyClass const& getObj() const { return instance_myclass; }
相关文章:
- 引用对象成员函数的成员函数
- 从 Base 引用对象调用派生类的成员
- 转换引用对象的边界框?
- 现代编译器会优化只引用对象子集的局部变量吗
- l值引用对象上的Constexpr成员函数:Clang和gcc不同意
- 将 const 类型引用对象注册为类成员对象C++
- Boost Intervocess:通过迭代通过从结构引用对象的映射进行迭代时
- 无法用2D矢量成员引用对象
- 在由引用对象传递中访问由引用对象传递的变量
- 如何使用QString引用对象名称
- 使用自动迭代器引用对象
- C++ 在另一个对象中引用对象的当前状态
- 使用共享对象和引用对象进行引用计数
- 未显式引用对象的全局对象构造函数在最终二进制文件 - LD 中被丢弃
- 引用对象的动态类型何时可以更改
- 引用对象内部的指针
- C++从全局静态函数中引用对象
- C++如何仅在没有其他人直接或间接引用对象指针时删除该指针
- 如何使用C++引用对象
- 为什么引用对象仅保存特定类型的引用