为什么调用与成员函数同名的非成员函数会产生错误 [英] Why calling a non-member function with the same name as a member function generates an error

查看:93
本文介绍了为什么调用与成员函数同名的非成员函数会产生错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下一个代码:

void f(int){}

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

此代码与错误消息(GCC)的格式不正确:错误:没有匹配的函数可以调用'A :: f(int)'或(clang)函数调用的参数过多,预​​期为0,值为1;您是说':: f'吗?

This code is not well-formed with the error message (GCC): error: no matching function for call to ‘A::f(int)’ or (clang) Too many arguments to function call, expected 0, have 1; did you mean '::f'?

为什么我需要使用 :: 调用与成员函数同名但具有不同签名的非成员函数?此要求的动机是什么?

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?

我认为编译器应该能够弄清楚我想把非成员函数作为签名是不同的(c甚至将其放在错误消息中!)。

I think the compiler should be able to figure it out I want to call the non-member function as the signature is different (clang even puts that in the error message!).

请不要将其标记为重复-这与在C ++中调用非成员函数在具有相同方法的类中

Please don't mark this as duplicate - it is a different question from this Calling in C++ a non member function inside a class with a method with the same

推荐答案


为什么使用::调用与成员函数同名但签名不同的非成员函数

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);

如果这被包含在 A ,那么 A :: g 的行为就会突然改变:它将调用它而不是 A :: f 。将重载集限制为在最窄的可用范围内使用的名称,可以防止这种意外损坏。

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.

这篇关于为什么调用与成员函数同名的非成员函数会产生错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆