Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 流式和条件运算符错误_C++ - Fatal编程技术网

C++ 流式和条件运算符错误

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

我最近在代码中遇到了一个bug,我认为这可能是一个常见的错误。我已经概括了这个错误,我想理解为什么这不会生成编译器警告或错误。提前谢谢

错误在于以下使用条件运算符和流式运算符来cout:

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;