使用命名空间和重载函数

3
我不明白为什么会出现“重载函数调用不明确”的错误。 在“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();
}

3
你的命名空间中有两个 foos。现在你应该使用 ::foo() 或者 second::foo() - Steve
1
你的期望是错误的。当你声明using namespace second时,你扩展了工作命名空间为second。为了澄清你想从哪个初始工作空间调用函数,你应该使用<namespace>::foo,全局命名空间的名称为空。 - 273K
3
不要使用 using namespace ... 参见此文章 - Peter VARGA
4个回答

3
在"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
这是因为你使用了命名空间 second;。这样做将函数 foo() 从命名空间 second 引入全局作用域。在全局作用域中,存在另一个具有完全相同签名的函数 foo()。现在,对于 first::foo()second::foo() 的调用都没问题。然而,在调用 foo() 时,编译器不知道它应该调用哪个函数,因为它们是模糊的,并且此时它们都在全局命名空间中。

1
首先,用

替换void main() { }
int main() {

 return 0;
}

其次,using namespace second; 应该在你想要调用特定 namespacemain() 内部,而不是全局地声明。
最后,如果你使用 ::作用域解析运算符,那么你就不需要在 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;
}

1
你的 using namespace second; 正是你出现错误的原因。这实际上告诉编译器将 second::foo 当作在全局命名空间中一样对待。所以现在你有两个 foo
顺便说一下,void main 不是有效的 C++ 语法。必须使用 int main

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接