构造函数中的srand()导致相同的数字?

时间:2017-06-05 08:55:41

标签: c++ srand

我有以下结构来随机生成一个整数字段:

GameManager::GameManager(){
    srand(time(NULL));
}

void GameManager::newGame(int sizen, int sizem) {

//ETC
    for(int i = 0; i < sizen; ++i){
        _gameField[i].resize(sizem);
        for(int j = 0; j < sizem; ++j){
            _gameField[i][j] = RandomColor(difficulty);
        }
    }
}

int GameManager::RandomColor(Difficulty diff){
    if(diff == Easy){
        return rand()%4+1;
    } else if(diff == Medium) {
        return rand()%5+1;
    }else{
        return rand()%6+1;
    }
}

但是,每次只生成相同的数字字段,就像播种不起作用一样。如果我将播种放在newGame()中,它每次都会产生不同的随机数。为什么种子在构造函数中不起作用?

修改

请在此处查看课程定义:

class GameManager : public QObject
{
    Q_OBJECT
public:
    GameManager();
    ~GameManager();

    int Size_n = 12;
    int Size_m = 7;

    Difficulty difficulty = Easy;

    void newGame(int sizen, int sizem);
    QVector<QVector<int> > _gameField;
    QVector<QPair<int,int> > _taboo;

private:
    int RandomColor(Difficulty diff);
};

0 个答案:

没有答案