此代码在第 6 行抛出错误。是因为 cout 流不允许它还是 ostream 中的某些冲突?

时间:2021-08-01 19:39:28

标签: c++ compiler-errors cout

#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 究竟是如何工作的吗?

1 个答案:

答案 0 :(得分:4)

请参阅此处了解运算符优先级: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;