打印出错误的值

时间:2015-09-17 11:27:03

标签: c++ visual-studio get set

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

ID:123姓名: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

1 个答案:

答案 0 :(得分:2)

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

更改

num = id;

id = num;

name相同。

此外,声明

exams[0, 1, 2] = 0;

没有按照您的预期执行操作,它只会将exams[2]初始化为sero,而其余部分则未初始化。表达式0, 1, 2使用comma operator

分别分配给阵列的所有成员,或使用constructor member initializer list(我推荐 all 初始化)。

相关问题