派生类继承基类赋值运算符?

Ami*_*mit 2 c++ inheritance assignment-operator

在我看来,派生类不继承基类赋值运算符,
如果派生类继承基类赋值运算符,请解释以下示例

在下面的代码中,我覆盖了派生类中的基类 operator=,以便派生类默认赋值运算符调用重载的 operator=

#include <iostream>  
using namespace std;      
class Base  
{  
    public:  
    Base(int lx = 0):x(lx)  
    {  
    }  

    virtual Base& operator=( const Base &rhs)  
    {  
        cout << "calling Assignment operator in Base" << endl;  
        return *this;  
    }

    private:  
    int x;     
};      


class Derived : public Base  
{  
    public:  
    Derived(int lx, int ly): Base(lx),y(ly)  
    {  
    }

    Base& operator=(const Base &rhs)  
    {  
        cout << "Assignment operator in Derived"<< endl;  
        return *this;  
    }  

    private:  
    int y;    
};  



int main()  
{  
    Derived d1(10,20);  
    Derived d2(30,40);  
    d1 = d2;  
}  
Run Code Online (Sandbox Code Playgroud)

它给出了输出

在 Base 中调用赋值运算符

我已经将基类 operator= 重写为派生类,所以如果派生类继承基类 operator= 那么它应该被 operator= 覆盖(我在派生类中写的),现在派生类默认 operator= 应该调用覆盖版本而不是来自基类 operator=。

Bo *_*son 5

编译器为 Derived 生成一个默认的赋值运算符(它隐藏了 Base 的运算符)。但是,默认赋值运算符会调用类成员和基类的所有赋值运算符。