静态 class 变量自行初始化为 100

Static class variable initializing to 100 by itself

这是我的第一个问题,如果我的格式有误,请见谅。

所以,进入正题 - 这是我的大学作业。目标是创建一个名为 Student 的 class,它有几个字段,并将实例存储在 Student 对象数组中。其中一项任务是在 class 中设置一个静态变量,用于跟踪已创建的 Student 实例的数量。为了澄清,我有一个 getData() 方法,它要求用户输入值,然后将当前对象的值设置为输入的值(基本上就像构造函数一样,这使得构造函数过时了,但他们希望我们那样做因为某些原因)。在 getData() 函数中,静态计数变量在构造函数中增加 1,并在析构函数中减少。

问题是由于某种原因,Student::amount 变量将自身设置为 100。每次我尝试从 main() 函数访问它时,它的 100 加上创建的学生数量,所以如果我们已经创建了 2 个学生,Student::amount 将等于 102。顺便说一下,我没有明确地将它设置为该数字,它也与数组的大小相匹配。

我对 C++ 还是比较陌生,我已经阅读和观看了一些 material 关于 OOP 如何在这里工作的内容,但我几乎没有触及表面。

如果我的问题表述不当,再次抱歉or/and 格式不当,我希望你能帮助我!

#include <iostream>
#include <string>
using namespace std;

class Date {
...
};

class Student {
    // Fields
private:
    string name = "";
    string PID = "";
    int marks[5]{ 0 };
    short course = 0;
public:
    // Count of all students
    static int amount;

    // Getters
    ...

    // Setters
    ...

    // Constructors
    Student(); // Default one, Student::amount gets raised by 1 there
    Student(string name, string PID, int marks[5], short course);

    // Destructor
    ~Student();

    // Methods
    void getData();
    void display(); // Display the information of a student
};

// Array of students
Student students[100];

// Student::Count
int Student::amount; // Initializes with 0 if not explicitly initialized

void Student::getData() {
    cin.ignore();
    cout << "\nName: "; getline(cin, name);
    cout << "PID: "; getline(cin, PID);
    cout << "Marks:\n";
    for (int i = 0; i < 5; i++)
    {
        cin >> marks[i];
    }
    cout << "Course: "; cin >> course;
    Student::amount++;
}

Student::Student(string name, string PID, int marks[5], short course) {
    this->setName(name);
    this->setPID(PID);
    this->setMarks(marks);
    this->setCourse(course);
    Student::amount++;
}

全局声明 Student students[100]; 在达到 main 之前调用默认 Student 构造函数 100 次。根据您的评论(您不提供构造函数实现),该构造函数将 amount 增加 1.

此处的解决方案是删除 Student::amount 并改为使用

std::vector<Student> students;

students.size() 将为您提供该容器中的学生人数。使用push_back将学生放入向量中。

一个非常粗略的至少广泛符合问题约束的替代方案是从默认构造函数中删除amount增量,以及除四参数构造函数。