2012-03-11 25 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()); 

否則你創建地圖的副本

相關問題