重载赋值运算符的继承

时间:2017-10-04 03:26:55

标签: c++ inheritance operator-overloading

C ++ Complete Reference说:“除了=运算符,运算符函数由派生类继承。”

但我无法理解以下代码的行为:

#include<iostream>
using namespace std;
int main(){

    class b{
        int i;
        public:
            int operator=(b parm){
                cout<<"base overload";
            };
    };
    class d: public b{
        int j;
        public:
    };



    b inst1,inst11;
    d inst2,inst22;
    int a;

   inst1=inst11;    //works because assignment operator  is overloaded for b

   inst2=inst22;  //If =operator function is not inherited then why does it output "base oberload"

   inst1=inst2;    //works because assignment overloaded for b

 // inst2=inst11;      //But if b was inherited then this should also work but it doesnt


}

我期待两个输出语句“基本过载”,但它输出三个为什么?这让我疯狂

1 个答案:

答案 0 :(得分:0)

operator=未被继承。但编译器将generate implicitly operator=用于类d,它会调用b::operator=来分配基础子对象。

  

运算符使用标量的内置赋值和类类型的复制赋值运算符,按初始化顺序执行对象基础和非静态成员的成员方式复制分配。

然后

inst2=inst22;  //If =operator function is not inherited then why does it output "base oberload"

此处调用生成的d::operator=;在其中调用b::operator=

inst1=inst2;    //works because assignment overloaded for b
这里调用

b::operator=,它期望b作为参数,inst2可以隐式转换为基类b

// inst2=inst11;      //But if b was inherited then this should also work but it doesnt
尝试在此处调用

d::operator=,它期望d作为参数,但inst11无法隐式转换为派生类d。< / p>