以静态方式使用Random类

Edd*_*223 0 c++ random static class

我正在做一个简单的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;
    }
};
Run Code Online (Sandbox Code Playgroud)

显然,C++不允许将整个类声明为static(这使得在C#中这么容易).我把所有的成员都改成了static.也没有static构造函数所以我没有办法初始化我,bool seeded除非我手动调用函数,这违背了目的.我可以改为使用常规构造函数,我必须在其中创建一个Random我不想做的实例.

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

Bil*_*eal 7

c ++不允许将整个类声明为静态

当然可以.

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. ;)
Run Code Online (Sandbox Code Playgroud)

实际上,没有理由把它放在课堂上.C++不会强迫你把所有东西都放在课堂上 - 这是有充分理由的.在C#中,你被迫将所有东西放入一个类中,并用静态方法等来声明事物,但这不是意识形态的C++.

你真的不能只采用ideomatic C#代码,并用C++编写,并期望它能很好地工作.它们是非常不同的语言,具有非常不同的要求和编程特征.

如果你想要一种思想的C++方法,那就不要上课了.srand在你的内部打电话main,并定义一个你的夹紧功能:

int RandomInteger(int high, int low)
{
    return (std::rand() % (high - low)) + low;
}
Run Code Online (Sandbox Code Playgroud)

编辑:当然,你最好使用新的随机数生成设施,并uniform_int_distribution获得你的钳位范围而不是rand.看到rand()有害的.

  • @Blazes:全局变量在C++中具有静态存储持续时间.C++定义了3个存储持续时间(好吧,在C++ 11中添加了`thread`存储持续时间):`automatic`("stack allocated"变量),`static`(全局变量和本地`static`变量),和` dynamic`(用`malloc`或`new`分配).自动变量一直存在,直到它们的块结束,动态变量一直存在,直到它们被调用`delete`或`free`,静态变量一直存在直到程序终止. (2认同)