静态构造函数在C ++?我需要初始化私有静态对象 [英] static constructors in C++? I need to initialize private static objects

查看:207
本文介绍了静态构造函数在C ++?我需要初始化私有静态对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想有一个具有私有静态数据成员的类(一个包含所有字符a-z的向量)。在java或C#中,我可以创建一个静态构造函数,它将在我创建类的任何实例之前运行,并设置类的静态数据成员。它只运行一次(因为变量是只读的,只需要设置一次),因为它是类的一个函数,它可以访问它的私有成员。我可以在构造函数中添加代码,以检查向量是否已初始化,如果没有初始化,则初始化它,但引入了许多必要的检查,并且看起来不是问题的最佳解决方案。

I want to have a class with a private static data member (a vector that contains all the characters a-z). 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.

我想到的是,由于变量将是只读的,它们只能是public static const,所以我可以在类外部设置它们,但是再一次,它看起来像一个丑陋的黑客。

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.

如果我不想在实例构造函数中初始化它们,可以在类中拥有私有静态数据成员? p>

Is it possible to have private static data members in a class if I don't want to initialize them in the instance constructor?

推荐答案

要获得相当于一个静态构造函数,您需要编写一个单独的普通类来保存静态数据,然后进行静态

To get the equivalent of a static constructor, you need to write a separate ordinary class to hold the static data and then make a static instance of that ordinary class.

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

};

这篇关于静态构造函数在C ++?我需要初始化私有静态对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆