我正在制作一个简单的 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/