C++ 流式和条件运算符错误
我最近在代码中遇到了一个bug,我认为这可能是一个常见的错误。我已经概括了这个错误,我想理解为什么这不会生成编译器警告或错误。提前谢谢 错误在于以下使用条件运算符和流式运算符来cout:C++ 流式和条件运算符错误,c++,C++,我最近在代码中遇到了一个bug,我认为这可能是一个常见的错误。我已经概括了这个错误,我想理解为什么这不会生成编译器警告或错误。提前谢谢 错误在于以下使用条件运算符和流式运算符来cout: int i=0; int array[] = {1}; std::cout << false ? array[i++] : 2; std::cout << std::endl << "i = " << i << std::endl; // outpu
int i=0;
int array[] = {1};
std::cout << false ? array[i++] : 2;
std::cout << std::endl << "i = " << i << std::endl;
// output:
// 0
// i = 1
此外,在条件操作后调用流式处理运算符会产生编译器错误:
int i=0;
int array[] = {1};
std::cout << false ? array[i++] : 2 << std::endl;
std::cout << std::endl << "i = " << i << std::endl;
// fails to compile
// error: invalid operands of types 'int' and '<unresolved overloaded function type>' to binary 'operator<<'
inti=0;
int数组[]={1};
标准::cout
inti=0;
标准::cout
我假设打印的第一个数字0是false的数字表示
对
我不确定编译器如何解释其余部分
?:
是三元条件运算符。第一子表达式(std::cout好的。操作顺序问题,通过明智地使用括号来解决。你有问题吗?啊,我想我现在才意识到。正在评估的条件是cout的结果。如果你看一张表,你会发现三元运算符在列表的下面。啊。谢谢,不好意思问。使用std::布拉尔法
int i=0;
int array[] = {1};
std::cout << false ? array[i++] : 2 << std::endl;
std::cout << std::endl << "i = " << i << std::endl;
// fails to compile
// error: invalid operands of types 'int' and '<unresolved overloaded function type>' to binary 'operator<<'
int i = 0;
std::cout << false ? array[i++] : 2;
main.cpp:7:20: warning: operator '?:' has lower precedence than '<<'; '<<' will be evaluated first [-Wparentheses]
std::cout << false ? array[i++] : 2;
~~~~~~~~~~~~~~~~~~ ^
main.cpp:7:20: note: place parentheses around the '<<' expression to silence this warning
std::cout << false ? array[i++] : 2;
^
main.cpp:7:20: note: place parentheses around the '?:' expression to evaluate it first
std::cout << false ? array[i++] : 2;