C ++操作符继承和重载 [英] C++ operator inheritance and overloading
问题描述
我有一个基类A和一个派生类B. A和B都定义了[]运算符,但是没有相同的参数类型。仍然,当我尝试对类型B的对象使用[]操作符与A arg C ++没有找到A的def这个。很烦人。什么是规则?
I have a base class A and a derived class B. A and B both define the [] operator but not with the same argument type. Still, when I try to use the [] operator on an object of type B with A arg C++ doesn't find A's def of this. Very annoying. What's the rule?
推荐答案
类B中的运算符隐藏类A中的运算符。一个重载超类中的方法的派生类。如果名称查找在 B
中找到名称匹配,它不会在 A
中查找,即使匹配不能调用 B
中找到的
The operator in class B hides the operator in class A. This is a problem with any method defined in a derived class that overloads a method in a super class. If name lookup finds a name match in B
it doesn't look in A
, even if the match(s) found in B
can't be called.
您需要将其放入B的范围:
You need to bring it into the scope of B:
class X{};
class Y{};
class A {
public:
auto operator[](X) {};
};
class B : public A {
public:
using A::operator[]; // <-- you need this
auto operator[](Y){};
};
int main() {
A a;
B b;
b[X{}]; // OK
b[Y{}]; // OK
}
这篇关于C ++操作符继承和重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!