【问题标题】:srand function in class [duplicate]类中的srand函数[重复]
【发布时间】:2018-03-22 18:43:09
【问题描述】:

我正在学习 C++,但我似乎找不到我的问题的答案。当我运行我的代码时,我没有得到任何编译器错误,但是当我调用一个函数“getVin()”(应该使用“generate()”函数生成一个随机数)时,它不会所以。它输出一个零。这是我的课程(来自头文件):

class Vehicle {
public:
    Vehicle();
    static int generate();
    const int getVin () { return m_vin; }

protected:
    float m_lla[3];
    const int m_vin = s_idgen;

private:
    static int s_idgen;
};

和定义(来自源文件):

int Vehicle::s_idgen = generate();

Vehicle::Vehicle() {
    m_lla[3] = 0;
}

int Vehicle::generate() {
    srand((int)time(0));
    return (rand() % 10000) + 1;
}

任何建议都会有所帮助,谢谢!

【问题讨论】:

  • 您应该只调用srand 一次。例如,time 函数通常以 为单位返回时间,这意味着如果您在一秒钟内多次调用 generate 函数,那么您会将种子重置为相同的值并获得相同的“随机”数字。此外,C++ 的 pseudo-random generation facilities 比普通的 srandrand 好得多,我建议你改用它们。
  • 想一想:这种情况什么时候发生? const int m_vin = s_idgen; s_idgen 什么时候设置好?
  • 不要认为该问题与建议的问题重复:OP 问题与重复调用 srand 无关,而是与静态变量的初始化顺序有关,根据@Serge Ballesta anwer。

标签: c++ oop random static srand


【解决方案1】:

我可以部分重现,所以我假设你被静态初始化惨败所困扰。我刚刚添加了:

Vehicle sveh; // static scoped

在 Vehicle 声明之后和任何方法或静态字段定义之前,然后

int main() {
    Vehicle veh;
    std::cout << veh.getVin() << std::endl;
    std::cout << sveh.getVin() << std::endl;
    return 0;
}

输出是:

1915
0

这意味着自动Vehicle 正确使用随机值(运行时随机,但对所有实例都通用...),而静态值在静态字段初始化之前被初始化。

【讨论】:

    【解决方案2】:

    在标题中,您可以:

    protected:
      const int m_vin = s_idgen;
    

    在您的源文件中,您可以:

    int Vehicle::s_idgen = generate();
    

    m_vin的初始化发生时,s_idgen的值是多少? generate() 尚未设置。试着打印出来,看看我的意思。

    尝试直接从您的函数返回s_idgen


    PS:考虑使用 &lt;random&gt; 代替 C 传统函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多