c++ - 派生类是否间接继承基类的赋值运算符?

标签 c++ inheritance assignment-operator

我试图理解这种行为,但我似乎不理解。请看这段代码:

#include <iostream>
using namespace std;

class Base
{
public:
    void operator=(const Base& rf)
    {
        cout << "base operator=" << endl;
        this->y = rf.y;
    }
    int y;
    Base() : y(100) { }
};

class Derived : public Base
{
public:
    int x;
    Derived() : x(100) { }
};

int main()
{
    Derived test;
    Derived test2;
    test2.x = 0;
    test2.y = 0;
    test.operator=(test2); // operator auto-generated for derived class but...
    cout << test.x << endl << test.y << endl;
    cin.ignore();
    return 0;
}

程序输出:

> base operator=
>  0
>  0

现在我感到困惑的是: 该规则表明派生类从不继承赋值运算符,而是创建自己的 operator= 但是在本示例中基类的 operator= 在派生类上被调用。

其次,我能够在派生类上显式调用赋值运算符,而派生类中又没有显式定义它。

现在,如果我理解正确的话,这意味着任何用户定义的基运算符总是在派生类上被调用?

最佳答案

生成的那些会自动调用基类赋值运算符。

// generated version looks basically like this
Derived& operator=(Derived const& other){
  Base::operator=(static_cast<Base const&>(other));
  x = other.x;
  return *this;
}

强制转换是为了避免像这样意外调用模板化的 Base::operator=:

template<class Other>
Base& operator=(Other const& other); // accepts everything

或者像这样的奇怪的:

// forward-declare 'Derived' outside of 'Base'
Base& operator=(Derived const& other); // accepts derived class (for whatever reason)

Second I was able to explicitly invoke an assigment operator on a derived class, which isn't in turn explicitly defined in the derived class.

编译器会自动声明一个赋值运算符,如果你不这样做并且你的类允许它(即没有引用成员和一些其他神秘的规则)并且另外定义它如果你实际上在某个地方使用它。

关于c++ - 派生类是否间接继承基类的赋值运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8867469/

相关文章:

c++ - 如何正确使用crypto++ Blowfish

javascript - 使用 "pseudoclassical"模式在 JavaScript 中实现成员变量继承

c# - 从基类更改属性 setter 行为

c++ - 重新实现 CMFCPropertyGridProperty 类 (MFC) 的最佳方式

c++ - 如何在 C++ 的 STL 容器值中拥有 const 成员?

C++ const重载赋值运算符机制

c++ - 未声明的 FTDI 标识符

c++ - 可能的编译器错误 : Weird results using boost bessel functions with Intel compiler between two machines?

C++矩阵类: overloading assignment operator

c++ - CUDA 计算能力向后兼容性