如何在C ++中仅使用一个实例创建类 [英] How to create class with only one instance in C++

查看:53
本文介绍了如何在C ++中仅使用一个实例创建类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中,有什么方法只允许一个类的一个实例吗?
如果有,请向我解释。谢谢。

Is there any way to allow only one instance of a class in C++? If there is, please expain to me. Thank you.

推荐答案

这是单人模式。您可以通过公共静态属性和私有构造函数来实现此目的:

This is the singleton pattern. You can achieve this via a public static attribute and a private constructor:

class Singleton {
    public:
        static Singleton * const singleton;
    private:
        Singleton(void) {}
};
Singleton * const Singleton::singleton = new Singleton();

编辑: Dan Watkins的观点很不错;如果您确实想对此严苛,则可以通过显式声明那些私有方法来禁止复制和分配:

Good point from Dan Watkins; If you really want to be draconian about it, you can disallow copy and assignment by also explicitly declaring those methods private:

    private:
        Singleton(void) {}
        Singleton(Singleton& other) {}
        Singleton& operator=(Singleton& other) {}

这篇关于如何在C ++中仅使用一个实例创建类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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