【问题标题】:Quickly assign all the members of a base object to a derived object in C++在 C++ 中快速将基础对象的所有成员分配给派生对象
【发布时间】: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) 并且没有接受Derivedoperator=(),那么base=derived 将起作用。
  • 请说明您问的是base = derived;,还是derived = base;

标签: c++ inheritance assignment-operator


【解决方案1】:

我想将 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;

【讨论】:

    【解决方案2】:

    我知道我们不能只使用运算符“=”将基础对象分配给其派生对象

    这不是真的。

    我们是否必须一一复制所有成员?喜欢: base.s1 =派生的.s1; base.s2 =派生的.s2; ... base.s100 = 派生的.s100;

    不是真的。正如 Danh 在第一条评论中提到的那样。

    base = derived 
    

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

    【讨论】:

      【解决方案3】:

      我知道我们不能只使用运算符“=”将基础对象分配给它 派生对象。

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

      static_cast<Base &>(derived)=base;
      

      库存示例:

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

      【讨论】:

      • 谢谢,我会试试这个 static_cast。但是,即使在这种情况下,这是一个好的做法吗?
      • @MM - 不符合 gcc 6.1.1: "tC:12:4: error: no match for 'operator=' (operand types are 'Derived' and 'Base')"跨度>
      • @SamVarshavchik 够公平
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-26
      • 2015-11-07
      • 1970-01-01
      • 2018-02-02
      • 2019-03-23
      相关资源
      最近更新 更多