【发布时间】:2017-02-03 06:08:40
【问题描述】:
假设我们有一个基类和一个派生类:
class Base {
string s1;
string s2;
...
string s100; // Hundreds of members
};
class Derived : public Base{
string s101;
};
我想将基础对象base 分配给派生对象derived。我知道我们不能只使用运算符“=”将基础对象分配给其派生对象。
我的问题是:我们必须将所有成员一一复制吗?喜欢:
derived.s1 = base.s1;
derived.s2 = base.s2;
...
derived.s100 = base.s100;
有没有更快或更简洁的方法来做到这一点?重载 operator= 与 返回的基础对象?
【问题讨论】:
-
base = 派生的?
-
派生对象不存在,我当时只有一个基础对象作为数据源。我想创建一个新的派生对象,分配其成员并将其放入容器中,例如地图。
-
那你为什么写'base.s1 = derived.s1'
-
假设
Base支持分配给Base) 并且没有接受Derived的operator=(),那么base=derived将起作用。 -
请说明您问的是
base = derived;,还是derived = base;
标签: c++ inheritance assignment-operator