c++ - 以静态方式使用 Random 类

标签 c++ class random static

我正在制作一个简单的 Random 类:

class Random
{
public:
    static bool seeded = false;

    static void SeedRandom( int number )
    {
        srand(number);
    }
    static int GetRandom(int low, int high)
    {
        if ( !seeded )
        {
            srand ((int)time(NULL));
        }
        return (rand() % (high - low)) + low;
    }
};

很明显,C++ 不允许将整个类声明为 static(这正是 C# 中如此简单的原因)。相反,我将所有成员设为 static。也没有 static 构造函数,所以我无法初始化我的 bool seeded 除非我手动调用一个函数,这违背了目的。我可以改为使用常规构造函数,在其中我必须创建 Random 的实例,但我不想这样做。

另外,有谁知道新的 C++0x 标准是否允许静态类和/或静态构造函数?

最佳答案

c++ doesn't allow declaring a whole class as static

当然可以。

class RandomClass
{
public:
    RandomClass()
    {
        srand(time(0));
    }
    int NextInt(int high, int low)
    {
        return (rand() % (high - low)) + low;
    }
}

RandomClass Random; //Global variable "Random" has static storage duration

//C# needs to explicitly allow this somehow because C# does not have global variables,
//which is why it allows applying the static keyword to a class. But this is not C#,
//and we have globals here. ;)

但实际上,没有理由将其放入类。 C++ 不会强制您将所有内容都放在类中——这是有充分理由的。在 C# 中,您被迫将所有内容放入类中并在静态方法中声明内容,但这不是理想的 C++

您真的不能只是采用理想的 C# 代码,然后用 C++ 编写,并期望它运行良好。它们是截然不同的语言,具有截然不同的要求和编程特征。

如果您想要一种理想的 C++ 方式来执行此操作,则根本不要创建类。在 main 中调用 srand,并定义一个执行钳位的函数:

int RandomInteger(int high, int low)
{
    return (std::rand() % (high - low)) + low;
}

编辑:当然,您最好使用新的随机数生成工具和uniform_int_distribution 代替rand< 来获取您的限制范围。参见 rand() considered harmful .

关于c++ - 以静态方式使用 Random 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5740976/

相关文章:

C++将高分辨率时钟与固定数字进行比较

c++ - 在 Qt 中处理多个 ui 文件

c++ - 如何将重音字母 (wchar_t) 转换为 char?

java - 如何为我的国际象棋游戏添加倒计时?

JavaScript - 从目录中选择一个随机页面

c++ - 在 Vista 上更新 KB3059317 后,MFC 程序挂起 : broken Comctl32. dll?

java - 静态嵌套类和普通类的区别

php - 列出给定类的所有方法,不包括 PHP 中父类的方法

ios - 按下按钮时播放随机声音 Swift 2.0

c++ - std::uniform_int_distribution 不够随机