Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

C++ operator inheritance and overloading

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...