You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++类代码cout输出void方法报invalid operands to binary expression错误

C++代码报错原因及修复方案

报错原因

编译器抛出invalid operands to binary expression错误的核心原因如下:

  • Animal类的showData成员函数返回值类型为void,即无任何返回值。你将an.showData(&x,&y)写在cout输出流后,相当于尝试输出一个不存在的void类型值,而C++标准库的输出流没有定义接收void类型的<<运算符重载,因此触发语法报错。
  • 额外逻辑问题:当前showData函数内部直接输出的是weight、age两个指针本身的内存地址,不是指针指向的存储的数值,如果你的需求是输出体重、年龄的实际值,需要对指针做解引用操作。另外main函数中的输入提示标注为输入height and weight,但后续变量被当做体重和年龄使用,存在语义不一致的问题。

修复方案

方案1:直接调用showData函数,不嵌套外层cout

因为showData内部已经实现了输出逻辑,不需要再外层套cout,将main函数中的对应行:

cout << an.showData(&x,&y) << endl;

修改为:

an.showData(&x,&y);

如果需要输出指针指向的实际数值,同步修改showData实现:

void showData(int *weight, int *age)
{
    cout << "The weight is " << *weight << " and the age is " << *age << endl;
}

方案2:修改showData返回值类型,适配外层cout输出

如果你希望保留外层cout输出的写法,将showData的返回值改为string类型即可:

string showData(int *weight, int *age)
{
    return "The weight is " + to_string(*weight) + " and the age is " + to_string(*age);
}

修改后原有的cout << an.showData(&x,&y) << endl;代码可以正常运行。


内容的提问来源于stack exchange,提问作者Shifty

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 16:27:00