c++ - 使用命名空间和重载函数

标签 c++ namespaces

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

this is the first foo
this is the second foo
this is the second 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();
}

最佳答案

Before "main", I declared to use namespace "second".

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

您可以明确指定要调用全局 foo,即

::foo();

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

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

关于c++ - 使用命名空间和重载函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49465238/

相关文章:

php - Laravel 5.7 : Argument 1 passed to

c++ - Visual Studio TDD 项目的代码覆盖工具

c++ - 使用 std::initializer_list 作为成员变量

c++ - 按标识从列表中删除对象

PHP 命名空间 : equivalent to C# using

C# 从 LinQ XDocument 加载数据表

namespaces - Squeak 是否支持命名空间?

c++ - 使用聚合初始值设定项声明空 C++ 数组

c++ - 为什么 g++ 4.9.0 默认有 std::isnan?

php - 找不到类 'App\Http\Controllers\DB',我也无法使用新模型