类型"int"和"<未解析的重载函数类型>"到二进制"运算符<<"的操作数无效

Invalid operands of types ‘int’ and ‘<unresolved overloaded function type>’ to binary ‘operator<<’

本文关键字:lt 类型 二进制 运算符 gt 无效 操作数 int 重载 函数      更新时间:2023-10-16

我试图将两个数组求和为第三个数组!!

int main()
{
   int RoadHeights[2000] , TopoHeights[2000] , Differences[4000] , i , n ;
   cout << "Enter the number of stations! " << endl;
   cin >> n;
   cout << "Enter the heights of stations on Road! " << endl;
   for ( i=0 ; i<n ; i++ )
      cin >> RoadHeights[i];
   cout << "Enter the heights of stations on Ground! " << endl;
   for ( i=0 ; i<n ; i++ )
      cin >> TopoHeights[i];
   cout << "Height differences are: " << endl;
   for ( i=0 ; i<n ; i++ )
      cout << Differences [4000] = RoadHeights[i] - TopoHeights[i] << endl;
   return 0;
}

2: Differences[4000]越界,且=运算符的优先级低于<<操作符,所以用括号把表达式括起来:

cout << (Differences [i] = RoadHeights[i] - TopoHeights[i]) << endl;

否则,首先计算cout << Differences[i],返回ostream&,有效地变成

cout << Differences[i]; 
cout = (RoadHeights[i] - TopoHeights[i]) << endl;

显然第二行是错误

这将解决你的编译器问题,但我猜你有更多的逻辑问题在那里。例如,硬编码数组大小,但用户输入的大小之后?如果n5000呢?试着用std::vector代替。

std::vector<int> RoadHeights, TopoHeights, Differences;
int i , n ;
cout << "Enter the number of stations! " << endl;
cin >> n;
RoadHeights.resize(n);
TopoHeights.resize(n);
Differences.resize(n);
// proceed as normal