【问题标题】:Is the assignment operator inherited or not?赋值运算符是否继承?
【发布时间】:2021-08-28 06:17:14
【问题描述】:

我知道赋值运算符不会被派生类继承,相反,如果没有重新声明,编译器将创建一个默认值。但是我不明白为什么下面代码sn-p的输出是Base operator=

#include  <iostream>
using namespace std;


class B {
protected:
    int h;
public:
        B& operator=(const B& ob){
        if (this!=&ob)         {
        h = ob.h;
        cout << "Base operator=\n";
        }
        return *this;
        }
};

class D: public B  {
protected:
    float r;
public:
};


int main() {

    D a, b;

    a = b;

    return 0;
}

那不是说在调用a = b 时基址B&amp; operator=(const B&amp; ob 不就继承了吗?我哪里错了?

【问题讨论】:

    标签: c++ inheritance operator-overloading


    【解决方案1】:

    生成的赋值是“所有的基础赋值,按照继承声明的顺序”,所以你生成的赋值本质上是

    D& operator=(const D& d)
    {
        B::operator=(d);
        return *this;
    }
    

    如果您要从 BC 派生 - 按此顺序; class D: B, C - 相当于

    D& operator=(const D& d)
    {
        B::operator=(d);
        C::operator=(d);
        return *this;
    }
    

    也就是说,赋值不是继承的,而是被使用的。

    【讨论】:

    • 如果你能证明为什么你的 B 分配高于 C 分配,那么奖励 ;-)
    • 奖金来了 ;-)
    【解决方案2】:

    使用表达式a = b,编译器为D 生成的赋值运算符调用B 中用户定义的赋值运算符。

    是的,你说得对,赋值运算符不是继承的。

    【讨论】:

    • 所以它不像普通函数那样直接调用,它生成了一个新的operator=function?就像编译器认为“我怎样才能生成一个新函数?”他决定使用基础中的功能?
    猜你喜欢
    • 2012-02-28
    • 2021-06-07
    • 2012-02-10
    • 2015-02-09
    • 1970-01-01
    • 1970-01-01
    • 2020-12-15
    • 2018-11-24
    • 2012-02-12
    相关资源
    最近更新 更多