Why calling a non-member function with the same name as a member function generates an error

后端 未结 4 485
广开言路
广开言路 2020-12-11 00:52

I have next code:

void f(int){}

struct A
{
    void f()
    {
        f(1);
    }
};

This code is not well-formed with the error message (

4条回答
  •  情话喂你
    2020-12-11 01:40

    Why do I need to use :: to call the non-member function with the same name as the member function, but with different signature

    Because those are the rules. Names in a nested scope hide entities with the same name in a wider scope.

    What is the motivation for this requirement?

    Consider the case where a member function calls another member with a signature that doesn't quite match:

    struct A {
        void f(double);
        void g() {f(42);}  // requires int->double conversion
    };
    

    Now suppose someone adds an unrelated function in the surrounding namespace

    void f(int);
    

    If this were included in the set of overloads within the scope of A, then suddenly the behaviour of A::g would change: it would call this instead of A::f. Restricting the overload set to names in the narrowest available scope prevents this kind of unexpected breakage.

    As you (and your helpful compiler) say, the outer name is still available (with qualification) if you need it.

提交回复
热议问题