派生类间接继承base的赋值运算符? [英] Do derived classes indirectly inherit base's assignment operator?

查看:224
本文介绍了派生类间接继承base的赋值运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解这个行为,但似乎我没有。请参阅以下代码:

I'm trying to understand this behaviour but it seems I don't. Please see this code:

#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 = 类。

Now where I'm confused is: The rule says that a derived class never inherits the assigment operator, instead it creates its own operator= however in this example base's operator= gets invoked on the derived class.

第二我可以在派生类上显式调用一个分配操作符,而不是在派生类中明确定义。

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.

现在如果我理解正确,这意味着任何用户定义的base操作符总是在派生类上被调用。

Now if I understand it correctly, this means that any user defined base's operator always gets invoked on the derived class?

推荐答案

生成的代码会自动调用<-em>基类赋值运算符。

The generated ones automatically call the base-class assignment operator.

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

演员可以避免对模板< c> Base :: operator = 就像这样:

The cast is there to avoid an accidential call to a templated Base::operator= like this one:

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.

如果你不允许,并且你的类允许它(即没有引用成员和一些其他奥术规则),另外定义 / em>如果你实际上在某处使用它。

The compiler automatically declares an assignment operator if you do not and your class allows it (i.e., no reference members and some other arcane rules) and additionally defines it if you actually use it somewhere.

这篇关于派生类间接继承base的赋值运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆