【问题标题】:error: no match for 'operator<<' (operand types are 'std::ostream' {aka 'std::basic_ostream<char>'} and 'void')| [closed]错误:'operator<<' 不匹配(操作数类型是 'std::ostream' {aka 'std::basic_ostream<char>'} 和 'void')| [关闭]
【发布时间】:2021-12-17 18:04:23
【问题描述】:

这是我的代码。我已经经历了很多次,做了很多改变仍然是同样的错误。

#include <iostream>

using namespace std;

void checkAge(int age){
    if(age >= 18){
        cout<< "As your age is above 18, you are eligible to vote. \n";
    }
    else{
        cout<< "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;
}

【问题讨论】:

  • checkAge 不返回任何值。尽管如此,它还是使用cout 自行输出字符串。所以checkAge(age); 没有cout &lt;&lt; 就足够了。
  • 不看checkAge内部,只看它的签名,你能知道cout &lt;&lt; checkAge(age)应该打印什么样的数据吗?

标签: c++ c++11


【解决方案1】:

您的函数checkAge 不返回任何内容。所以只需从

中删除cout
cout << checkAge(age);

也就是将上面的语句替换为:

checkAge(age);

解决方案 2

另一个解决方案是从checkAge 返回一个int。例如,您可以将函数定义更改为:

#include <iostream>

using namespace std;

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


    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-18
    • 1970-01-01
    • 1970-01-01
    • 2021-08-09
    • 2016-12-01
    相关资源
    最近更新 更多