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

标签 c++ reference

我正在尝试拥有一个私有(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/

相关文章:

c# - 如何实现自动选择html中的项目并点击提交?

javascript - 为什么我不能在我的 View 中引用 JavaScript 文件?

Java 窗口生成器 : runtime error

java - Java 中引用的概念问题

c++ - "inline"函数定义的目的是什么?

c++ - GetCPUDescriptorHandleForHeapStart 堆栈损坏

c++ - 从成员构造函数中抛出异常(大括号初始值设定项与初始值设定项列表)

struct - 使用结构存储对非复制值的引用

c++ - 返回对切片对象(父类(super class)型)的引用

c++ - CreateFile2、WriteFile 和 ReadFile : how can I enforce 16 byte alignment?