如何在c++中拥有私有成员变量和对它们的引用

How to have private member variables and references to them in c++

本文关键字:变量 引用 成员 c++ 拥有      更新时间:2023-10-16

我正在尝试拥有一个私有实例变量,并使用一个getter方法来返回对该私有ivar的引用(我知道我可以将该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 << "printIvarn";
        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;
}

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

umap_str_str umap = getPrivateIvar();

现在正在创建一个新的umap_str_str对象,它将是_umap私有成员的副本。你需要使用一个参考:

umap_str_str &umap(getPrivateIvar());

您正在复制引用。您需要:

umap_str_str& umap = getPrivateIvar();

getPrivateIvar()确实为您的会员返回了一个别名,但是当您进行时

umap_str_str umap = getPrivateIvar();

您可以有效地调用副本构造函数,从而处理副本。

您可以编写

umap_str_str& umap (getPrivateIvar());

否则,您将创建地图的副本