[英]How do I get my method to recognize my object value in c++
我一直在自学C ++,但遇到了一些问题。 希望你能指导我。 基本上在main方法中,我创建了一个学生对象“ s1”,并且尝试使用在学生类下创建的方法“ getResults(double gpa)”来获取其GPA的结果。
首先,我遇到一个错误,指出“对二进制表达式无效的操作数('ostream'(又名'basic_ostream')和void')
我了解在StackOverflow上发布了与此错误有关的一些问题,但我需要有关此错误含义的特定上下文的一些帮助和说明。
我需要帮助的另一件事是,由于我正在使用s1对象来调用该方法,因此有一种方法可以编写方法“ getResults()”,使其可以自动检索学生对象的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
返回类型,这意味着它实际上不返回任何内容 。 正因为如此,不要试图cout
在主此功能的结果。
考虑以下编辑:
// Your result is printed within this function
s1.getResult(s1GPA);
// Print a new line if you wish
cout << endl;
另外,由于您的getResults
并没有真正得到任何东西,因此建议将名称更改为诸如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";
}
}
当你在你的主的说法,它试图cout
任何操作 ,因为getResult
是无效:
cout << s1.getResult(s1GPA) << endl;
// ^^^^^^^^^^^^^^^^^^^
// This doesn't return anything for cout to output.
这就是为什么只需要调用getResult
而不是尝试cout
它的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.