问题描述
静态成员有时会让我困惑。我理解如何使用 c来初始化一个简单的内置类型,例如 int $ c>,你放在一个.cpp文件,但我有以下类别:
Static members confuse me sometimes. I understand how to initialize a simple built in type such as int with something along the lines of int myClass::statVar = 10;, which you place in a .cpp file, but I have something of the following sort:
class myClass { public: // Some methods... protected: static RandomGenerator itsGenerator; }
基本思想很简单: myClass 需要访问其成员函数之一的随机生成器。我也可以只有几个实例的发电机,因为每个对象是相当大。然而, RandomGenerator 类型需要被初始化,可以说,通过调用 RandomGenerator :: Randomize(),编译器不会允许你这样做,因为它不是一个const右值(是吗?)。
The basic idea is simple enough: myClass needs access to a random generator for one of its member functions. I also can have only a few instances of the generator since each object is quite big. However, the RandomGenerator type needs to be "initialized", so to speak, by a call to RandomGenerator::Randomize(), which the compiler won't allow you to do since it's not a const rvalue (is that right?).
那么我该如何使这项工作呢?
So how can I make this work?
或者我不应该使用静态变量
Or perhaps should I not make use of a static variable in this case, and do it some other way?
推荐答案
您可以创建包含的封装类。RandomGenerator 中,并在其构造函数中调用 RandomGenerator :: Randomize 。
You could create wrapper class which will hold RandomGenerator instance in it and will call RandomGenerator::Randomize in its constructor.
这篇关于对象静态成员的初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!