派生运算符在派生类中不可用 [英] Assignment operator not available in derived class

查看:120
本文介绍了派生运算符在派生类中不可用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基类中的赋值运算符似乎在派生类中不可用.给出以下代码:

The assignment operator in base class does not seem to be available in derived class. Given this code:

#include <iostream>

class A{
    int value;
public:
    A& operator=(int value){
        this->value = value;
        return *this;
    }
};

class B : public A{};

int main(){
    B b;
    b = 0; // Does not work
    return 0;
}

GCC 6.4说:

错误:"operator ="不匹配(操作数类型为"B"和"int")

error: no match for 'operator=' (operand types are 'B' and 'int')

发生了什么事?

推荐答案

当我们自己不提供自己时,每个类至少都有一个隐式定义的赋值运算符.

Every class has at least one assignment operator implicitly defined when we don't provide one ourselves.

当派生类中的成员函数定义的名称与基类中的成员的名称相同时,它将隐藏该名称的所有基类定义.

And when a member function in a derived class is defined with the same name as a member in the base class, it hides all the base class definitions for that name.

您可以使用using声明,但要警告它会拉 all 名为operator=的成员,并允许这样的代码:

You can use a using declaration, but be warned that it will pull all the members named operator= and allow code like this:

A a;
B b;
b = a;

有些怀疑.

这篇关于派生运算符在派生类中不可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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