超载在名称空间中定义的函数

Overloading a function defined in a namespace

本文关键字:定义 函数 空间 超载      更新时间:2023-10-16

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

#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)

基本上是在说

what名称空间内,在此处定义print函数

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

标准状态的

§13.1,"当在同一范围中为单个名称指定两个或更多不同的声明时,该名称被说 要超载。"

函数的过载必须在彼此的相同范围内。这就是语言的工作方式。