其他分享
首页 > 其他分享> > c – 派生类继承基类赋值运算符?

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

作者:互联网

在我看来,Derived类不会继承基类Assignment运算符
如果Derived类继承了Base类赋值运算符,请解释下面的例子

在下面的代码中,我在Derived中重写了基类operator =,因此Derived类的默认赋值运算符调用了重载的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;  
}  

它给出了输出

calling Assignment operator in Base

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

解决方法:

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

标签:c,assignment-operator,inheritance
来源: https://codeday.me/bug/20191002/1843718.html