[英]Is it necessary to overload the assignment operator and the copy constructor for a class A which has a data member of another class B?
I have a class List
, which has as a member of pointer of type Vector
(my own class).我有一个类
List
,它作为Vector
类型指针的成员(我自己的类)。 For this class I have overloaded the assignment operator and redefined the copy-constructor.对于这个类,我重载了赋值运算符并重新定义了复制构造函数。
The problem is that I am not sure if a have to do the same thing for a new class, which has a member of type List
(not dynamically allocated).问题是我不确定是否必须为一个新类做同样的事情,它有一个
List
类型的成员(不是动态分配的)。
class List {
Vector *l;
int len;
// assignment operator and copy-constructor defined here
}
class Graf_Neorientat : public Graf {
List L;
...
};
The member variable L
in your Graf_Neorientat
class can be assigned and copied just the same way as if it was a normal variable in your program. Graf_Neorientat
类中的成员变量L
可以像程序中的普通变量一样分配和复制。 So you don't need to do write again that code in Graf_Neorientat
to be able to copy L
when Graf_Neorientat
is copied.因此,您无需在
Graf_Neorientat
再次编写该代码即可在复制Graf_Neorientat
时复制L
Now, probably what you wanted to ask instead is if you need to do something "extra" in Graf_Neorientat
to make it also copyable (and copy L
when doing so).现在,您可能想问的是,您是否需要在
Graf_Neorientat
做一些“额外”的Graf_Neorientat
以使其也可复制(并在这样做时复制L
)。
Assuming Graf
is copyable (or ignoring Graf
), the answer is no.假设
Graf
是可复制的(或忽略Graf
),答案是否定的。 If your List
class is copyable, then your Graf_Neorientat
will be copyable.如果您的
List
类是可复制的,那么您的Graf_Neorientat
将是可复制的。 The compiler will define implicitly the assignment operator and copy constructor for you, which will call in turn the List
ones to copy the L
member appropriately.编译器将为您隐式定义赋值运算符和复制构造函数,它们将依次调用
List
来适当地复制L
成员。
Of course, you can disable copyability yourself in Graf_Neorientat
if you want in several ways, and you can also define a different assignment operator and copy constructor if you wish to do something else (rare).当然,你可以禁用自己复制性
Graf_Neorientat
如果你在几个方面想,你也可以定义不同的赋值操作符和拷贝构造函数,如果你想做些别的事情(罕见)。 But, as given in your example, Graf_Neorientat
will do what you expect.但是,如您的示例所示,
Graf_Neorientat
会做您期望的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.