成员函数隐藏自由功能 [英] member function hiding free function

查看:177
本文介绍了成员函数隐藏自由功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  void foo(int)
{
}

class X
{
void foo
{
}

void bar()
{
foo(42);
//错误:没有匹配的函数调用'X :: foo(int)'
//注意:候选是:
//注意:void X :: foo b $ b //注:候选期望有0个参数,1提供
}
};为什么C ++无法调用自由函数(这是唯一具有正确签名的函数)?



<

解决方案

逻辑原因是一致性




  • 假设按照建议,编译器将 foo(42)解析为
    :: foo c>
  • $ c $ c> X :: foo(int)然后
    foo(42)将解析为 X :: foo(int)。这是不一致的。


这也是为什么派生类函数隐藏基类函数时有类似名称的原因。 p>

这种情况可以通过两种方式解决:



(1)提供完全限定名称c> :: foo(42)



(2)使用使用 ;例如

  void bar()
{
using :: foo;
foo(42);
}


void foo(int)
{
}

class X
{
    void foo()
    {
    }

    void bar()
    {
        foo(42);
        // error: no matching function for call to 'X::foo(int)'
        // note: candidate is:
        // note: void X::foo()
        // note:   candidate expects 0 arguments, 1 provided        
    }
};

Why is C++ unable to call the free function (which is the only one with the correct signature)?

解决方案

The logical reason is Consistency.

  • Suppose as per the suggestion, compiler resolves foo(42) to ::foo(int).
  • Now after sometime, if you change X::foo() to X::foo(int) then foo(42) will be resolved to X::foo(int). Which is not consistent.

That is the also the reason why derived class function hides base class function when there are similar names.

Such cases can be resolved in 2 ways;

(1) Give fully qualified name (e.g. ::foo(42))

(2) Use using utility; e.g.

void bar()
{
  using ::foo;
  foo(42);
}

这篇关于成员函数隐藏自由功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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