创建复制的成员引用变量指的是副本的成员,而不是原始成员 [英] Making a copied member reference variable refer to a member of the copy and not of the original

查看:135
本文介绍了创建复制的成员引用变量指的是副本的成员,而不是原始成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一个代码,其中结构具有成员变量 bar 和引用 bar 的成员引用变量。例如:

Consider a code where a struct has a member variable bar and a member reference variable that refers to bar. For instance:

struct Foo{
    double bar;
    double &bar_ref=bar;
};

void receivesFoo(Foo cp_foo){
    //&cp_foo.bar_ref is the same as &my_foo.bar_ref
 }

int main(){
    Foo my_foo;
    receivesFoo(my_foo);
    return 0;
}

问题是如果你复制一个例如,将它传递给一个函数, cp_foo.bar_ref 将引用 my_foo.bar ,而不是 cp_foo.bar 。我如何使它引用 cp_foo.bar 而不是?

The problem is that if you make a copy of a Foo by, for example, passing it to a function, cp_foo.bar_ref will refer to my_foo.bar and not to cp_foo.bar. How can I make it refer to cp_foo.bar instead?

注意:我使用这些引用变量为命名方便,因为一些教程使它看起来像一个可能的用法, d而不是避免与宏相关的所有可读性问题。

Note: I use these references variables for naming convenience, as some tutorials make it look like a possible use and I'd rather avoid all the readability issues associated with macros.

推荐答案

另一种方法是使用副本的/ language / initializer_list =nofollow>成员初始值列表构造函数:

One alternative would be to use the member initializer list of a copy constructor:

struct Foo{
    double bar;
    double &bar_ref;
    Foo():bar_ref(bar){}
    Foo(const Foo& a):bar_ref(bar){}
};

这似乎工作,但是增加了不得不使用类似的代码维护两个单独的初始化列表。如果允许使用C ++ 11,可以通过执行以下操作避免它:

This seems to work, but adds an inconvenience of having to maintain two separate initialization lists with similar code. If you are allowed to use C++11 you can avoid it by doing:

struct Foo{
    double bar;
    double &bar_ref=bar;
    Foo(){}
    Foo(const Foo& a){}
};

注意,如果您使用指针,可能会遇到类似的问题

Notice you may encounter similar issues if you use pointers

作为@juanchopanza评论,您还可以通过使用default关键字来改进前面的示例。有关详情,请参见此问题

As @juanchopanza comments, you may also improve the previous example by using the default keyword. See this question for more details:

struct Foo{
    double bar;
    double &bar_ref=bar;
    Foo()=default;
    Foo(const Foo& a){}
};

这篇关于创建复制的成员引用变量指的是副本的成员,而不是原始成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆