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

后端 未结 4 487
广开言路
广开言路 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:33

    Why do I need to use :: to call the non-member function with the same name as the member function, but with different signature? What is the motivation for this requirement?

    That is the whole point of having namespaces. A local (closer-scoped) name is preferred and more visible over a global name. Since a struct is again a scope, its f is shadowing the visibility of ::f. When you've to have the global one, you've to say you do. Why?

    This is provided as a feature to make sure you can peacefully call functions you defined assuming they would get called, and when you need one from a different namespace, say the standard library, you'd state that explicitly, like std::. It's just a clean form of disambiguation, without leaving room for chance to play its part.

提交回复
热议问题