在c++中快速将基对象的所有成员赋值给派生对象

Quickly assign all the members of a base object to a derived object in C++

本文关键字:对象 成员 赋值 派生 c++      更新时间:2023-10-16

假设我们有一个基类和一个派生类:

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;

是否有更快或更简洁的方法来做到这一点?重载操作符= with返回的基对象?

我想把一个Base对象赋值给一个Derived对象。

为其提供过载operator=:

class Derived : public Base {
    Derived& operator=(const Base& b) { 
        Base::operator=(b); // call operator= of Base
        s101 = something;   // set sth to s101 if necessary
        return *this; 
    }
};

那么你可以

Base b;
// ...
Derived d;
// ...
d = b;

我知道我们不能仅仅使用操作符"="将基对象赋值给它的派生的对象。

当然可以(在这个问题的上下文中):

static_cast<Base &>(derived)=base;
股票的例子:

class Base {};
class Derived : public Base {};
void foo()
{
    Derived d;
    Base b;
    static_cast<Base &>(d)=b;
}

我知道我们不能仅仅使用操作符"="将基对象赋值给它的派生对象

那不是真的。

我们必须一个一个地复制所有成员吗?如:基地。S1 = derived.s1;基地。S2 = derived.s2;…基地。

没有。正如Danh在第一条评论中提到的。

base = derived 

就足够了,因为它执行隐式动态上转换(即从指针到派生转换到指针到基)。见http://www.cplusplus.com/doc/tutorial/typecasting/