【问题标题】:using namespace & overloaded function使用命名空间和重载函数
【发布时间】:2018-03-24 13:27:56
【问题描述】:

我不明白为什么会收到错误“对重载函数的模糊调用”。 在“main”之前,我声明使用命名空间“second”。 我的预期输出是:

这是第一个 foo
这是第二个 foo
这是第二个 foo

#include <iostream>
using namespace std;

namespace first {
    void foo() {
        cout << "this is the first foo" << endl;
    }
}

namespace second {
    void foo() {
        cout << "this is the second foo" << endl;
    }
}


void foo() {
    cout << "this is just foo" << endl;
}


using namespace second;
void main() {
    first::foo();
    second::foo();
    foo();
}

【问题讨论】:

  • 您的命名空间中有两个foos。您现在应该使用::foo()second::foo()
  • 你的期望是错误的。当您声明using namespace second 时,您使用second 扩展工作命名空间。为了明确你想从哪个初始工作区调用函数,你应该使用&lt;namepspace&gt;::foo,全局命名空间的名称为空。
  • 不要使用using namespace ... See this article

标签: c++ namespaces


【解决方案1】:

在“main”之前,我声明使用命名空间“second”。

当您这样做时,second::foo 被引入全局命名空间,然后对于 foo();second::foo::foo 都是有效的候选者。

您可以指定要显式调用全局foo,即

::foo();

或者在main() 中使用using-declaration 而不是using-directive,例如

int main() {
    using second::foo;
    first::foo();
    second::foo();
    foo();
}

【讨论】:

    【解决方案2】:

    发生这种情况的原因是因为您的:using namespace second;

    执行此操作时,您将 foo() 命名空间中的函数 foo() 限定为全局范围。在全局范围内,存在另一个具有完全相同签名的函数foo()。现在,您可以致电 first::foo()second::foo()。但是,当您调用foo() 时,编译器不知道它应该只调用foo() 还是second::foo(),因为它们是模棱两可的,此时它们都在全局命名空间中。

    【讨论】:

      【解决方案3】:

      您的using namespace second; 正是您收到错误的原因。它实际上告诉编译器将second::foo 视为在全局命名空间中。所以现在你有两个foos。

      顺便说一句,void main 不是有效的 C++。必须是int main

      【讨论】:

        【解决方案4】:

        首先,将void main() { }替换为

        int main() {
        
         return 0;
        }
        

        其次,using namespace second; 应该在 main() 中,您要从其中调用特定的 namespace,而不是全局。

        最后,如果您使用的是::scope resolution operator,那么您不必在main() 中提及using namespace second,使用其中一个即可。

        像下面那样做

        int main() {
                first::foo(); /* first foo will be called */
                second::foo(); /* second foo() will be called */
                foo(); /* global foo() will be called */
                return 0;
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-03-19
          • 2015-07-05
          • 1970-01-01
          • 2011-05-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-09-10
          相关资源
          最近更新 更多