重载命名空间中定义的函数

Cur*_*ous 3 c++ overloading c++11

为什么下面的代码是非法的?

#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;
}
Run Code Online (Sandbox Code Playgroud)

用clang编译时得到的错误-std=c++14

error: out-of-line definition of 'print' does not match any declaration in namespace 'what'
Run Code Online (Sandbox Code Playgroud)

我知道问题的解决方法,但我想知道为什么编译器认为我试图定义函数(print)而不是重载它.

Gre*_*g M 5

它不适合你的原因是因为语法

void what::print(const string& str)
Run Code Online (Sandbox Code Playgroud)

基本上是说

what命名空间内,在print这里定义函数

如果要在其命名空间之外定义函数,则必须事先在命名空间中声明它.

标准的第13.1节规定,"当在同一范围内为单个名称指定了两个或更多不同的声明时,该名称被称为过载."

函数的重载必须在彼此的相同范围内.这就是语言的运作方式.