超载在名称空间中定义的函数
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)
基本上是在说
在
what
名称空间内,在此处定义
如果要在其名称空间之外定义函数,则必须事先在名称空间中声明。
标准状态的函数的过载必须在彼此的相同范围内。这就是语言的工作方式。§13.1,"当在同一范围中为单个名称指定两个或更多不同的声明时,该名称被说 要超载。"
相关文章:
- 在命名空间中定义函数还是限定函数
- 为什么在定义函数之前先声明它
- 使用用户定义函数的字符串反转
- 用户定义函数中的指针和输入
- 这个c++代码是如何在没有定义函数的情况下运行的
- 具有外部"c"和程序集的未定义函数
- 已定义函数时出现 G++ "未定义的引用"错误
- 将自定义函数传递到基抽象类中以延迟执行
- C++使用 rand 定义函数语法
- Arduino:在 loop() 和自定义函数中运行相同的代码时出现问题
- 将具有固定签名的自定义函数名称注入 CRTP
- 使用定义函数模板别名
- 是否可以使用单个定义定义函数的常量和常规版本?(使用模板,自动,decltype等)
- 在内联程序集中定义函数和从 C++ 调用时出现问题
- 在 Metal 着色器代码中,如何定义函数的 in/out 参数变量?
- 声明和定义函数静态会产生"undefined reference to function_name()"
- 朋友定义函数的名称空间是什么
- 介子 对用户定义函数的未定义引用
- 如何使用 "using" 关键字定义函数原型/签名
- 在 C 结构中定义C++函数