【问题标题】:derived assignment operator calling the one from a base派生赋值运算符从基础调用
【发布时间】:2013-03-03 09:11:29
【问题描述】:

In the best rated answer to the question from this link,我不明白派生的赋值运算符如何从基类调用赋值运算符,即这部分代码中的这个:

Derived& operator=(const Derived& d)
{
    Base::operator=(d);
    additional_ = d.additional_;
    return *this;
}

做什么

Base::operator=(d)

是什么意思?它有什么作用?干杯!

【问题讨论】:

    标签: c++ inheritance operator-overloading assignment-operator


    【解决方案1】:

    Base::operator= 调用Base 类版本的operator= 来复制对象中属于Base 的部分,然后派生类复制其余部分。由于基类已经正确完成了所有需要的工作,为什么要重复工作,只需重用即可。那么让我们来看这个简化的例子:

    class Base
    {
       std::string
          s1 ;
       int
          i1 ;
       public:
         Base& operator =( const Base& b)  // method #1
         {
            // trvial probably not good practice example
            s1 = b.s1 ;
            i1 = b.i1 ;
    
            return *this ;
         }
    } ;
    
    class Derived : Base
    {
       double
         d1 ;
       public:
         Derived& operator =(const Derived& d ) // method #2
         {
           // trvial probably not good practice example
           Base::operator=(d) ;
           d1 = d.d1 ;
           return *this ;
    
         }
    
    } ;
    

    Derived 将有三个成员变量,两个来自Bases1i1,一个是它自己的d1。所以Base::operator= 调用了我标记为method #1 的东西,它复制了DerivedBase 继承的两个变量,它们是s1i1,所以剩下要复制的就是d1method #2 负责的。

    【讨论】:

      【解决方案2】:

      这只是对当前对象的成员函数的调用。当前对象继承了一个标准名称为Base::operator= 的函数,您可以像调用任何其他非静态成员函数一样调用它。

      【讨论】:

      • Ben:哦,所以我需要考虑在派生对象上调用“Base::operator=(d)”(就像任何其他成员函数一样)!我认为“整个函数”作用于对象,我没有想过在函数的实际主体中这样做。真的,真的。因此,这会处理分配操作的基础部分,然后我当然需要分配 Derived 具有的任何额外数据数据。知道了,非常感谢。
      猜你喜欢
      • 2016-07-10
      • 2012-02-12
      • 1970-01-01
      • 1970-01-01
      • 2020-02-16
      • 1970-01-01
      • 2012-06-05
      • 2012-02-10
      • 2022-06-22
      相关资源
      最近更新 更多