[英]Printing out the wrong value
I'm trying to write a program that takes the grades and prints out the following: 我正在尝试编写一个程序,将成绩打分并打印出以下内容:
ID:123 NAME:John GRADE:78 ID:123名称:约翰等级:78
but instead I'm getting: 但是相反,我得到了:
ID:-842150451 NAME: GRADE: 78 ID:-842150451名称:等级:78
Can you guys help me and give me some extra tips to make my code cleaner since I'm fairly new to C++. 你们能帮我吗,并给我一些额外的提示,以使我的代码更整洁,因为我对C ++相当陌生。
Student.h 学生
#ifndef STUDENT_H
#define STUDENT_H
#include <iostream>
#include <string>
using namespace std;
class Student {
public:
Student(int num, string text);
int getID();
void setExamGrade(int a, int b);
int getOverallGrade();
void display();
string getName();
string name;
int id;
int exams[3];
int sum;
int average;
};
#endif
Student.cpp 学生.cpp
#ifndef STUDENT_CPP
#define STUDENT_CPP
#include "Student.h"
#include <iostream>
#include <string>
using namespace std;
Student::Student(int num, string text)
{
num = id;
text = name;
exams[0, 1, 2] = 0;
}
int Student::getID() {
return id;
}
string Student::getName() {
return name;
}
void Student::setExamGrade(int a, int b) {
exams[a] = b;
}
int Student::getOverallGrade() {
sum = exams[0] + exams[1] + exams[2];
average = sum / 3;
return average;
}
void Student::display() {
cout << "ID: " << getID();
cout << " NAME: " << getName();
cout << " GRADE: " << getOverallGrade() << endl;
}
#endif
gradebook.cpp 成绩簿
#ifndef GRADEBOOK_CPP
#define GRADEBOOK_CPP
#include "Student.h"
#include <iostream>
using namespace std;
int main() {
Student *s = new Student(123, "John");
s->setExamGrade(0, 80);
s->setExamGrade(1, 60);
s->setExamGrade(2, 95);
s->display();
delete s;
return 0;
}
#endif
You never assign to id
in the constructor, hence it's uninitialized and you will have undefined behavior when you print it. 您永远不会在构造函数中分配给
id
,因此它是未初始化的,并且在打印时将具有未定义的行为 。
Change 更改
num = id;
to 至
id = num;
Same with the name
. 与
name
相同。
Also, the statement 另外,声明
exams[0, 1, 2] = 0;
doesn't do what you expect it to do, it only initializes exams[2]
to sero, and leaves the rest uninitialized. 不会执行您期望的操作,只会将
exams[2]
初始化为血清,而其余未初始化。 The expression 0, 1, 2
uses the comma operator . 表达式
0, 1, 2
使用逗号运算符 。
Either assign to all members of the array separately, or use a constructor member initializer list (which I recommend for all the initialization). 要么分别分配给数组的所有成员,要么使用构造函数成员初始化器列表 (我建议所有初始化使用)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.