复制具有引用类型的成员变量的C ++类 [英] Copying a C++ class with a member variable of reference type

查看:122
本文介绍了复制具有引用类型的成员变量的C ++类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类存储对其父的引用,引用在构造函数中传递。如果我试图复制一个实例,我得到一个错误错误C2582:'操作符='函数不可用推测到参考是不可分配的。

I've a class which stores a reference to its parent, the reference is passed in the constructor. If I try to copy an instance I get an error "error C2582: 'operator =' function is unavailable" presumably down to the reference being non-assignable.

例如(过度简化但我认为有关键点):

e.g (over-simplified but I think has the key points):

class MyClass
{
public:
 MyClass(OtherClass &parent) : parent(parent) {}
private:
 OtherClass &parent;
};

MyClass obj(*this);
.
.
.
obj = MyClass(*this);


推荐答案

是的,如果您需要支持分配指针而不是引用几乎是你唯一的选择。

Yes, if you need to support assignment, making it a pointer instead of a reference is nearly your only choice.

这篇关于复制具有引用类型的成员变量的C ++类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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