C++ 是否可以返回对私有对象的引用并阻止更改

C++ Is it possible to return a reference to a private object and preventing change?

本文关键字:引用 对象 是否 返回 C++      更新时间:2023-10-16

我需要返回对我编写的类的私有成员的引用。我是这样做的:

在MyClass2.h中,我有以下行

MyClass* getObj(){return &instance_myclass;}

我将确保我的代码不会更改 instance_myclass 的任何值。但只是为了确保,有没有办法只读地返回此引用,以便我无法更改其值?或者,根据定义,这是不可能的?

您当前返回的不是引用,而是指针。

要返回引用,请使用:

MyClass& getObj() { return instance_myclass; }

如果你想通过该引用防止修改,只需让它const(当你使用它时,也使函数const):

MyClass const& getObj() const { return instance_myclass; }