赋值运算符在派生类中不可用 [英] Assignment operator not available in derived class
问题描述
基类中的赋值运算符在派生类中似乎不可用.鉴于此代码:
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 声明,但要注意它会拉所有名为 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屋!