+ -
当前位置:首页 → 问答吧 →  C++ 编写一个类,这个只能被实例化一次 (单例模式)

C++ 编写一个类,这个只能被实例化一次 (单例模式)

时间:2011-12-20

来源:互联网

急!!!!!!!!
  它的机制是什么 求解

作者: zengmin135   发布时间: 2011-12-20

C/C++ code
#include <iostream>

using std::cout;
using std::endl;

class Myjob
{
public:

    static Myjob* GetInstance(int a, int b);

    static void dispose(void);

    void show(void);

private:

    int x1, x2;

    Myjob(int a, int b);

     ~Myjob();

    static Myjob *m_pInstance;
};

// 单例初始化
Myjob* Myjob::m_pInstance(NULL);

Myjob::Myjob(int a, int b) : x1(a), x2(b)
{

}

Myjob::~Myjob(void)
{

}

// 释放资源
void Myjob::dispose(void)
{
    if (Myjob::m_pInstance != NULL)
    {
        delete Myjob::m_pInstance;
        Myjob::m_pInstance = NULL;
    }
}

Myjob* Myjob::GetInstance(int a, int b)
{
    if (m_pInstance == NULL)
    {
        m_pInstance = new Myjob(a, b);
    }
    return m_pInstance;
}

void Myjob::show(void)
{
    cout << this->x1 << " " << this->x2 << endl;
}

int main()
{
    Myjob *instance(Myjob::GetInstance(1, 2));
    instance->show();
    Myjob::dispose();// 不过单例一般很少涉及释放代码
    return 0;
}

作者: mougaidong   发布时间: 2011-12-20

引用楼主 zengmin135 的回复:
急!!!!!!!!
它的机制是什么 求解


他的机制是把构造函数设为私有,所以一般的函数不能访问,所以不能构造也就不能有别的对象存在.再利用成员函数有这个访问权限的特点,在成员函数内部构成唯一的对象供外部使用.

作者: mingliang1212   发布时间: 2011-12-20

1楼单线程用基本可以了,就是代码风格不敢恭维

作者: linux_qt   发布时间: 2011-12-20