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

C++编译提示no match for 'operator<<'错误该如何解决?

错误根因

你遇到的编译报错核心原因是:std::ostream的operator<<输出运算符没有对应void类型的重载实现,你代码中错误地尝试输出无返回值函数的执行结果。
你定义的checkAge函数返回类型为void,执行后不会返回任何可被输出的值,但你在main函数中编写了cout << checkAge(age);语句,要求cout输出checkAge的返回值,触发了类型不匹配的编译错误。

修复方案

有两种常见修复方式,按需选择即可:

  • 方案1:直接调用checkAge函数即可,无需嵌套cout。该函数内部已经实现了结果打印逻辑,不需要额外输出。
    修改后的main函数代码示例:
int main()
{
    int age;
    cout << "Enter your age. \n";
    cin >> age;
    checkAge(age);
    return 0;
}
  • 方案2:修改checkAge函数的返回类型为std::string,把提示文本作为返回值返回,保留cout << checkAge(age)的写法。
    完整修改后代码示例:
#include <iostream>
#include <string>
using namespace std;

string checkAge(int age){
    if(age >= 18){
        return "As your age is above 18, you are eligible to vote. \n";
    }
    else{
        return "As your age is below 18, you aren't eligible to vote. \n";
    }
}
int main()
{
    int age;
    cout << "Enter your age. \n";
    cin >> age;
    cout << checkAge(age);
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 18:45:04