【发布时间】:2023-04-03 11:17:01
【问题描述】:
我今天在阅读this answer,注意到字符数组前面有一个加号,但不知道它是什么意思。
考虑到我删除它时的编译错误,我可以猜测它有助于编译器推断返回类型,但我不知道它是如何工作的。
测试代码(也是here):
#include <iostream>
using namespace std;
auto& operator<<(std::ostream& os, const char (&s)[2]) {
return os << (*s == ' ' && !s[1] ? +"\n" : +s);
}
int main() {
cout << "Hello" << " " << "world" << " " << 2018;
return 0;
}
当删除 加号 符号 (sample) 时,它不会编译:
main.cpp: 在函数'auto& operator
main.cpp:6:48: 错误:在扣除'auto'之前使用'auto& operator
return os << (*s == ' ' && !s[1] ? "\n" : s); ^main.cpp:在函数'int main()'中:
main.cpp:10:24: 错误:在扣除'auto'之前使用'auto& operator
cout << "Hello" << " " << "world" << " " << 2018; ^~~
【问题讨论】:
-
好在我使用
auto&作为返回类型,编译器错误比堆栈溢出更容易调试。