How to use base class's assignment operator in C++

看了android下的代码,好长时间没看了,有个关于C++的知识点不是很清楚,查了下:

如何使用基类中的赋值运算符?

引述自http://stackoverflow.com/questions/1226634/how-to-use-base-classs-constructors-and-assignment-operator-in-c

参考:《C++ Primer》4ed_CN  p_495

编译器的默认设置:

struct base
{
   base() { std::cout << "base()" << std::endl; }
   base( base const & ) { std::cout << "base(base const &)" << std::endl; }
   base& operator=( base const & ) { std::cout << "base::=" << std::endl; }
};
struct derived : public base
{
   // compiler will generate:
   // derived() : base() {}
   // derived( derived const & d ) : base( d ) {}
   // derived& operator=( derived const & rhs ) {
   //    base::operator=( rhs );
   //    return *this;
   // }
};
int main()
{
   derived d1;      // will printout base()
   derived d2 = d1; // will printout base(base const &)
   d2 = d1;         // will printout base::=
}

如果我们在派生类中自己定义了拷贝构造函数、"="重载运算符,那么我们就需要显示的调用基类中的拷贝构造函数和基类中的“=”重载运算符。

class Base
{
    /* .. */
};

class Derive: public Base
{
    //如果没有显式调用Base(d),则调用Base中的无参的Base拷贝构造函数
    Derived(const Derived &d): Base(d) 
    {
        /* ... */
    }

    Derived &Derived::operator=(const Derived &rhs)
    {
        if(this != &rhs)
        {       
            Base::operator=(rhs);
            /* ... */
        }       

        return *this;
    }
};
原文地址:https://www.cnblogs.com/openix/p/3251293.html