You need to enable JavaScript to run this app. C++ for循环内调用void函数触发E0349无匹配运算符错误
优惠活动
大模型
产品
解决方案
定价
更多

C++ for循环内调用void函数触发E0349无匹配运算符错误

E0349报错根因

disp2xInt函数声明返回值为void,无有效返回值可传递给调用方。代码中cout << disp2xInt(i) << "\n"的写法,试图将void类型的返回结果传入输出流,而cout未定义接收void类型的<<运算符,因此触发无匹配运算符的编译报错。

修复方法

  • 直接移除for循环内对disp2xInt(i)的cout包裹:该函数内部已自带完整输出逻辑,直接调用即可完成打印,不需要把返回值传入输出流
  • 若必须保留cout << 函数调用的写法,需将disp2xInt的返回值类型修改为可直接输出的字符串类型,在函数内部完成文本拼接后返回给外部打印

修正后可直接运行的代码

#include <iostream>
#include <iomanip>
#include <string>
#include <cstdlib>

using namespace std;

void disp2xInt(int num);

int main() {
    atexit([] {system("pause"); });

    cout << "Jacob" << endl;
    cout << "ELET115N" << endl << endl;

    for (int i = 0; i < 5; i++) { 
        disp2xInt(i);
        cout << "Hello world!!!\n"; 
    }
    disp2xInt(9);

    return 0;
}

void disp2xInt(int n) {
    cout << "2 x " << n;
    cout << " = " << n * 2; 
    cout << endl;
}

如果需要保留原cout << disp2xInt(i)的写法,可替换disp2xInt的实现为如下版本:

#include <string>
string disp2xInt(int n) {
    return "2 x " + std::to_string(n) + " = " + std::to_string(n * 2) + "\n";
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.18 18:36:04