派生类赋值操作符

    赋值操作符通常与复制构造函数类似:如果派生类定义了自己的赋值操作符,

则该操作符必须对基类部分进行显式赋值。

    // Base :: operator = ( const Base & ) not invoked automatically 

    Derived & Derived:: operator=( const Derived &rhs )

    {

        if( this != &ths ) {

           Base::operator = ( rhs ); //assigns the base part

            //do whatever needed to clean up the old value in the derived part

            // assign the members from the derived

            }

           return *this; 

        }

    赋值操作符必须防止自身赋值。假定左右操作数不同,则调用Base类的赋值操作符

给基类部分赋值。该操作符可以由类定义,也可以是合成赋值操作符,这没什么关系--

我们可以直接调用它。基类操作符将释放左操作数中基类部分的值,并赋以来自rhs的新值。

该操作符执行完毕后,接着要做的是为派生类中的成员赋值。


猜你喜欢

转载自blog.csdn.net/weixin_38756546/article/details/80969037
今日推荐