在继承 class 中使用 srand time null 获取相同的值

Getting same values with srand time null in Inheritance class

我正在尝试修改我在 class 中学到的内容,并使用 "Student" class 进行简单的继承。 每当我创建一个学生时,它都会创建 StudentStats,正如您在代码中看到的那样,它应该在构造函数中具有随机值。但我总是从构造函数中得到相同的值。 我没有看到缺少什么,我在构造函数中包含了 time.h 和 srand(time(null)) 。

这可能是初学者的问题,但我真的看不出有什么问题:/

这位同学class:

#pragma once
#include <iostream>
#include <string>
#include "Personne.h"
#include "PTUT.h"
#include "Marks.h"
#include "StudentStats.h"
#include "StudentClass.h"

using namespace std;

class PTUT;
class StudentClass;
class Etudiant : public Personne, public Marks, public StudentStats

这是 StudentStats 的构造函数:

#include "StudentStats.h"
#include <iomanip>
#include <time.h>

StudentStats::StudentStats()
{
    srand(time(NULL));
    Morale = (rand() % 81) + 20 ;
    MathLevel = (rand() % 81) + 20;
    ProgLevel = (rand() % 81) + 20;
    NetworkDBLevel = (rand() % 81) + 20;
    GeneralLevel = (rand() % 81) + 20;
}

我得到的结果(我在 main 中创建了 4 个学生,每个学生的统计数据用“--------”分隔):

Results

转至 Adrian Mole 的评论,我得到了答案。

我声明了一个名为 "Seeded" 的静态 bool 并且我第一次调用构造函数时它将它从 false 更改为 True,所以下次我调用构造函数时它不会尝试重新播种。

答案:每次我调用构造函数时我都会重新播种它(多次调用 srand time null)所以我声明了一个静态 bool 用于调用 srand time null 一次。