打印出错误的值

Printing out the wrong value

我正在尝试编写一个获取成绩并打印出以下内容的程序:

ID:123 NAME:John GRADE:78

但我得到的是:

ID:-842150451 姓名:年级:78

由于我是 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

#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

你永远不会在构造函数中分配给 id,因此它是未初始化的,当你打印它时你将有 未定义的行为

改变

num = id;

id = num;

name相同。


另外,声明

exams[0, 1, 2] = 0;

并没有按照您的预期去做,它只将 exams[2] 初始化为 sero,其余的未初始化。表达式 0, 1, 2 使用 comma operator.

要么单独分配给数组的所有成员,要么使用 constructor member initializer list(我建议 all 初始化)。