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



我正在努力修改我在课堂上学到的东西,并用"Student"类制作一个简单的继承。每当我创建一个学生时,它都会创建StudentStats,正如您在代码中看到的那样,它应该在构造函数中具有随机值。但我总是从构造函数中得到相同的值。我看不出缺少了什么,我在构造函数中包含了time.h和srand(time(null((。

这可能是一个初学者的问题,但我真的不知道出了什么问题:/

这是学生班:

#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;
}

我得到的结果(我总共创建了4个学生,每个学生的统计数据用"--------"分隔(:

结果

根据Adrian Mole的评论,我得到了答案。

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

答:每次我调用构造函数时,我都会重新设置它的种子(多次调用srand-time null(,所以我声明了一个静态布尔,用于调用srand-time null一次。

最新更新