static constructors in C++? I need to initialize private static objects
I want to have a class with a private static data member (a vector that contains all the characters az). In java or C#, I can just make a "static constructor" that will run before I make any instances of the class, and sets up the static data members of the class. It only gets run once (as the variables are read only and only need to be set once) and since it's a function of the class it can access its private members. I could add code in the constructor that checks to see if the vector is initialized, and initialize it if it's not, but that introduces many necessary checks and doesn't seem like the optimal solution to the problem.
The thought occurs to me that since the variables will be read only, they can just be public static const, so I can set them once outside the class, but once again, it seems sort of like an ugly hack.
Is it possible to have private static data members in a class if I don't want to initialize them in the instance constructor?
要获得静态构造函数的等价物,您需要编写一个单独的普通类来保存静态数据,然后创建该普通类的静态实例。
class StaticStuff
{
std::vector<char> letters_;
public:
StaticStuff()
{
for (char c = 'a'; c <= 'z'; c++)
letters_.push_back(c);
}
// provide some way to get at letters_
};
class Elsewhere
{
static StaticStuff staticStuff; // constructor runs once, single instance
};
Well you can have
class MyClass
{
public:
static vector<char> a;
static class _init
{
public:
_init() { for(char i='a'; i<='z'; i++) a.push_back(i); }
} _initializer;
};
Don't forget (in the .cpp) this:
vector<char> MyClass::a;
MyClass::_init MyClass::_initializer;
The program will still link without the second line, but the initializer will not be executed.
In the .h file:
class MyClass {
private:
static int myValue;
};
In the .cpp file:
#include "myclass.h"
int MyClass::myValue = 0;
链接地址: http://www.djcxy.com/p/96348.html
上一篇: C ++静态成员初始化(模板乐趣里面)