此代码在第 6 行引发错误。是因为 cout 流不允许还是 ostream 中的一些冲突?


#include<iostream>
using namespace std;
int main() {
int a=4,b;
cout<<b=a*a;
return 0;
}

它显示

"error: no match for 'operator=' (operand types are 'std::basic_ostream<char>' and 'char')"

如果它必须与cout有关,有人能告诉我cin和cout究竟是如何工作的吗?

查看操作符优先级:https://en.cppreference.com/w/cpp/language/operator_precedence.

<<为第7位。=排在第16位。*排在第5位。因此这一行被解析为

(std::cout << b ) = (a * a);

不能将int分配给std::cout。改成这样:

int a = 4;
int b = a*a;
std::cout << b;

最新更新