重载命名空间中定义的函数
Overloading a function defined in a namespace
为什么下面的代码是非法的?
#include <iostream>
using namespace std;
namespace what {
void print(int count) {
cout << count << endl;
}
}
void what::print(const string& str) {
cout << str << endl;
}
int main() {
what::print(1);
what::print("aa");
return 0;
}
我用clang和-std=c++14
编译时得到的错误是
error: out-of-line definition of 'print' does not match any declaration in namespace 'what'
我知道问题的解决方法,但我想知道为什么编译器认为我正在尝试定义函数 (print
) 而不是重载它。
它对你不起作用的原因是语法
void what::print(const string& str)
基本上是在说
inside the what
namespace, define the print
function here
如果你想在它的命名空间之外定义一个函数,你必须事先在命名空间中声明它。
§13.1 of the standard states, "When two or more different declarations are specified for a single name in the same scope, that name is said
to be overloaded."
一个函数的重载必须在彼此相同的范围内。这就是语言的工作原理。
为什么下面的代码是非法的?
#include <iostream>
using namespace std;
namespace what {
void print(int count) {
cout << count << endl;
}
}
void what::print(const string& str) {
cout << str << endl;
}
int main() {
what::print(1);
what::print("aa");
return 0;
}
我用clang和-std=c++14
编译时得到的错误是
error: out-of-line definition of 'print' does not match any declaration in namespace 'what'
我知道问题的解决方法,但我想知道为什么编译器认为我正在尝试定义函数 (print
) 而不是重载它。
它对你不起作用的原因是语法
void what::print(const string& str)
基本上是在说
inside the
what
namespace, define the
如果你想在它的命名空间之外定义一个函数,你必须事先在命名空间中声明它。
§13.1 of the standard states, "When two or more different declarations are specified for a single name in the same scope, that name is said to be overloaded."
一个函数的重载必须在彼此相同的范围内。这就是语言的工作原理。