gpt4 book ai didi

c++ - "Invalid operands to binary expression (ostream and void)"是什么意思,如何修复?

转载 作者:行者123 更新时间:2023-11-28 02:15:26 27 4
gpt4 key购买 nike

我遇到一个错误:

Invalid operands to binary expression ('ostream' (aka 'basic_ostream') and 'void')

我知道 StackOverflow 上发布了一些与此错误相关的问题,但我需要一些有关此错误含义的特定上下文的帮助和解释。

main() 函数中,我创建了一个名为 s1 的学生对象。错误发生在 main() 中,我试图使用 Student 类的方法获取他的 GPA 结果 getResults(double gpa).

#include <iostream>

using namespace std;

class Human{
protected: string name;
protected: int age;

public: Human(){
name = "Unknown";
age = 5;
}

public:
Human(string name, int age){
this->name = name;
this->age = age;
}

string getName(){
return name;
}

int getAge(){
return age;
}

void setName(string name){
this->name = name;
}

void setAge(int age){
this->age = age;
}
};

class Student: public Human{
protected: string school;
protected: double gpa;

public:
Student(string name, int age, string school, double gpa) : Human(name, age){
this->school = school;
this->gpa = gpa;
}

double getGPA(){
return gpa;
}

string getSchool(){
return school;
}

void setGPA(double gpa){
this->gpa = gpa;
}

void setSchool(string school){
this->school = school;
}

void getResult(double gpa){
if (gpa < 3.0) {
cout << "You did well!";
} else {
cout << "Try harder next time";
}
}

};

int main() {
Student s1 ("John", 23, 'm', "University of Chicago", 3.4);
double s1GPA = s1.getGPA();
cout << s1.getResult(s1GPA) << endl;
return 0;
}

最佳答案

目前,您的 getResults 函数有一个 void 返回类型,这意味着它实际上不返回任何东西。因此,不要尝试在 main.c 中cout 这个函数的结果。

考虑以下编辑:

// Your result is printed within this function
s1.getResult(s1GPA);

// Print a new line if you wish
cout << endl;

此外,由于您的 getResults 并没有真正get 任何东西,我建议将名称更改为类似 printResults 的名称。

注意

请注意,在您的 getResult 中,它没有返回任何东西,因为它是空的。在此函数中,您只是使用 cout 将文本输出到控制台:

// Notice that this function doesn't actually return anything
void getResult(double gpa){
if (gpa < 3.0) {
// Output this message to console
cout << "You did well!";
} else {
// Output this message to console
cout << "Try harder next time";
}
}

当您在 main 中有语句时,它会尝试cout nothing 因为getResult 是空的:

cout << s1.getResult(s1GPA) << endl;
// ^^^^^^^^^^^^^^^^^^^
// This doesn't return anything for cout to output.

这就是为什么您只需要调用 getResult 而不是尝试 cout 的原因。

关于c++ - "Invalid operands to binary expression (ostream and void)"是什么意思,如何修复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34163958/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com