【问题标题】:Inheritance of Overloaded assignment Operator重载赋值运算符的继承
【发布时间】:2017-10-04 03:26:55
【问题描述】:

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


}

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

【问题讨论】:

    标签: c++ inheritance operator-overloading


    【解决方案1】:

    operator= 没有被继承。但是编译器将为类d 提供generate implicitly 和operator=,它调用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。

    【讨论】:

      猜你喜欢
      • 2012-02-28
      • 2021-08-28
      • 2021-06-07
      • 2015-02-09
      • 1970-01-01
      • 2018-05-09
      • 1970-01-01
      • 2011-12-05
      • 2020-12-15
      相关资源
      最近更新 更多