c++ operator =重载继承,是否需要在派生类中重新定义,尽管在基类中定义

C++ operator = overload inherited, is it necessary to redefine in the derived class though defined in the base class?

本文关键字:定义 基类 新定义 派生 重载 operator 继承 是否 c++      更新时间:2023-10-16

假设我有这样的c++代码:

class Base {
public:
 Base& operator=(const Base&);
};
class Derivate : public Base {
public:
};

我有一个main where

Derivate d1;
//Something on d1
Derivate d2 = d1;

在这种情况下,基类的操作符=会调用吗?我有一些代码,基本上做这样的事情,但调试与gdb我没有看到任何调用这样的操作符。

在这种情况下,有必要在派生类中重新定义操作符吗?

不,实际上你是在调用复制构造函数,因为你在构造d2的同时将d1赋值给d2,因此这里没有调用赋值操作符:

#include <iostream>
using namespace std;
class Base 
{
    public:
        Base& operator = (const Base&);
};
Base& Base::operator = (const Base&)
{
    cout << "assignment operator" << endl;
    // implementation here
    return *this;
}
class Derivate : public Base
{
    public:
        Derivate(){}
        Derivate(const Derivate& rhs){cout << "copy constructor" << endl;}
};
int main()
{
    Derivate d1;
    //Something on d1
    Derivate d2 = d1; // copy constructor not assignment operstor
    //Derivate d2(d1); // is the same as above calling cpy ctor
    d2 = d1; // here assignment operator is called
    return 0;
}
  • 为什么d2 = d1;调用基赋值操作符?

,因为如果你不提供派生类的赋值操作符,编译器会为你定义一个,如下所示:

Derivate& operator = (const Base& rhs); // not Derivate

因此,只要传递const引用而不是派生引用,派生类就会调用基类的赋值操作符。

  • 赋值操作符实际上是继承的:

在基类中设置私有作用域并查看结果