2012-03-11 95 views
0

我想要一个私有实例变量并使用一个返回对该私有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; 
} 

回答

4

在这一行中,您正在使用getPrivateIvar()方法,该方法返回一个引用。但是,您将它存储在类型umap_str_str的变量:

umap_str_str umap = getPrivateIvar(); 

正在发生的事情是,你正在创建一个新的umap_str_str对象,这将是_UMap私有成员的副本。您需要使用参考代替:

umap_str_str &umap(getPrivateIvar()); 
3

您正在复制参考。您需要:当你做

umap_str_str umap = getPrivateIvar(); 

你有效地调用拷贝构造函数

umap_str_str& umap = getPrivateIvar(); 

getPrivateIvar()并返回一个别名为您的会员,但是,从而对一个副本。

1

你可以写

umap_str_str& umap (getPrivateIvar()); 

否则你创建地图的副本