我需要返回对我写的Class的私有成员的引用。我是这样做的:
在MyClass2.h中,我有以下行
- (void)doSomeStuff:(nonnull NSDictionary<NSString *, NSString *> *)stuff;
我将确保我的代码不会更改instance_myclass的任何值。但只是为了确保,是否有一种方法可以返回此参考只读,以便我无法更改其值?或者,根据定义,这是不可能的?
答案 0 :(得分:5)
您目前不会返回引用,而是指针。
要返回参考,请使用:
MyClass& getObj() { return instance_myclass; }
如果您想阻止通过该引用进行修改,只需将其设为const
(当您使用该引用时,也可以创建函数const
):
MyClass const& getObj() const { return instance_myclass; }