首页 > 解决方案 > C++ - 初始化静态成员自己的方法

问题描述

是否可以使用自己的方法初始化静态成员,例如。初始化()?

例子:

class Foo
{
//some private variables
public:
static Bar example;
//some methods
}

然后在 main.cpp 中调用它,如:

Foo::example.initialize(argument);

当然,它不起作用。它也缺乏封装,因为变量是公共的。我希望它是私有的并且只初始化一次。除了用方法初始化它之外,我没有任何其他选择。

标签: c++oopmethodsstaticinitialization

解决方案


初始化对象的默认方式应该是它的默认构造函数。

如果真的需要,那么可以使用单例(注意它是反模式:什么是反模式?,还有单例有什么不好?

class Singleton
{
public:
    static const Bar& getBarInstance()
    {
        static Bar bar;

        return bar;
    }
};

这只会被初始化一次。


推荐阅读