我想要一个私有实例变量并使用一个返回对该私有ivar的引用的getter方法(我知道我只能让公共iar)。如何在C++中使用私有成员变量和对它们的引用
当我在使用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;
}