使用私有构造函数静态初始化

时间:2016-04-24 15:10:16

标签: c++

在类中,我有一个静态成员,表示该类的单例实例:

Factorial(0) = 1,
Factorial(1) = 1 * 1 = 1,
Factorial(2) = 1 * 2 = 2,
Factorial(3) = 2 * 3 = 6

为了防止更多实例,我将构造函数设为私有。现在我无法初始化静态var,因为初始化程序无法访问私有成员。这是我在.cpp文件中使用的代码:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <script src="https://code.jquery.com/jquery-2.2.3.min.js" charset="utf-8"></script>
        <style>
            .title{
                float: left;
                background-color: #51D7FF;
                margin-right: 10px;
                width: 80px;
                text-align: center;
            }
            .current{
                background: #4DFFE4;
            }
        </style>
        <script>
            $(document).ready(function(){
                var myDate = new Date();
                $('.title1').addClass('current');
                $('.title').click(function(){
                    $(this).addClass('current');
                    $(this).siblings().removeClass('current');
                }); 
            });
        </script>
    </head>
    <body>
        <div class="title title1">title1</div>
        <div class="title title2">title2</div>
        <div class="title title3">title3</div>

    </body>
</html>

工厂方法也无济于事,因为它也必须是公开的。我还能做些什么来完成这项工作?注意:如果可能的话,我想避免使用典型的class A { public: static const std::shared_ptr<A> INSTANCE; private: A(); }; 方法。

2 个答案:

答案 0 :(得分:5)

您无法使用make_shared,但您可以直接创建实例:

const std::shared_ptr<A> A::INSTANCE { new A };

答案 1 :(得分:0)

静态成员的初始化与构造函数无关,因此全局语句确实是正确的方法。它不适合你吗?

编辑:我刚刚意识到你出于某些原因试图避免使用单例访问方法。听起来像Borg pattern一样可疑。 :)与你的具体问题无关,但我建议你重新考虑。

相关问题