我正在尝试拥有一个私有(private)实例变量并使用返回对该私有(private) ivar 的引用的 getter 方法(我知道我可以将 ivar 公开)。
当我在使用 getter 方法后修改变量时,它似乎是在修改一个拷贝,而不是原始的 ivar。有什么想法吗?
#include <iostream>
#include <tr1/unordered_map>
#include <tr1/functional>
#include <tr1/utility>
typedef std::tr1::unordered_map<std::string, std::string> umap_str_str;
class Parent {
public:
//add an item to the private ivar
void prepareIvar(bool useGetter)
{
std::pair<std::string, std::string> item("myKey" , "myValue");
if(useGetter){
//getting the reference and updating it doesn't work
umap_str_str umap = getPrivateIvar();
umap.insert( item );
}else {
//accessing the private ivar directly does work
_UMap.insert( item );
}
}
void printIvar()
{
std::cout << "printIvar\n";
for( auto it : _UMap){
std::cout << "\tKEY: " << it.first << "VALUE: " << it.second << std::endl;
}
}
//get a reference to the private ivar
umap_str_str& getPrivateIvar()
{
return _UMap;
}
private:
umap_str_str _UMap;
};
int main(int argc, const char * argv[])
{
Parent *p = new Parent();
p->prepareIvar(true);//use the getter first
p->printIvar();//it doesn't print the right info
p->prepareIvar(false);//access the private ivar directly
p->printIvar();//prints as expected
return 0;
}
最佳答案
在这一行中,您使用了 getPrivateIvar() 方法,它返回一个引用。但是,您将其存储在 umap_str_str 类型的变量中:
umap_str_str umap = getPrivateIvar();
发生的事情是您正在创建一个新的 umap_str_str 对象,它将是 _UMap 私有(private)成员的拷贝。您需要改用引用:
umap_str_str &umap(getPrivateIvar());
关于c++ - 如何在 C++ 中拥有私有(private)成员变量和对它们的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9658396/