C++只能实例一个对象的类

一、只能实例化一个对象,在C++中用静态指针成员存储此类的实例,把构造函数设为私有,然后设置静态成员函数来得到此指针。

例子:

#ifndef ONEOBJECT_H
#define ONEOBJECT_H

//如果你用的编译器不支持C++11就取消下面的那句注释
//#define NULL nullptr

class OneObject
{
public :
    static OneObject * GetObject();
    ~OneObject();

private:
    OneObject(){};
    static OneObject * p ;
};

OneObject * OneObject::p = nullptr;

OneObject * OneObject::GetObject()
{
    if (nullptr == p)
    {
        p = new OneObject;
    }

    return p;
}

OneObject::~OneObject()
{
    if (p != nullptr)
    {
        delete p;
        p = nullptr;
    }
}

#endif

 

二、也是需要构造函数为私有或者保护,用静态成员函数实现<此方法来自Qt源码>:

class OneObject
{
public :
    static OneObject & GetObject()
    {
           static OneObject one;
           return one;
    }
    ~OneObject();

private:
    OneObject(){};
};

JAVA的也是类似,只是java废弃了指针,是通过引用实现的,不需要考虑内存的释放:

class A
{
	private static A aa = new A();
	public static A getA()。
	{
		return aa;
	}
	private A(){}
}

3 thoughts on “C++只能实例一个对象的类”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.