Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...