超载分配运算符的继承

Inheritance of Overloaded assignment Operator

本文关键字:继承 运算符 分配 超载      更新时间:2023-10-16

c 完整参考说:"除了=操作员,操作员函数由派生类继承。"

,但我了解以下代码的行为:

#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

}

我期望两个输出语句"基本过载",但它正在输出三个为什么?这让我发疯

operator=未继承。但是编译器将对d类隐含生成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