错误:与"运算符<<"不匹配(操作数类型为"std::ostream" {aka 'std::basic_ostream'<char>} 和 'void')|



这是我的代码。我已经经历了多次,做出了许多改变——仍然是同一个错误。

#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

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;
}

相关内容

最新更新