类的单例代码实现

♀尐吖头ヾ 提交于 2020-02-01 04:28:09

 single.h:

#ifndef SINGLE_H
#define SINGLE_H


class single
{
private:
    static single *p;
protected:
    single();

public:
    static single *makesignle();
    static void releasesingle();
};

#endif // SINGLE_H

single.cpp:

#include "single.h"
#include <iostream>

single *single::p=NULL;


single::single()
{

}

single *single::makesignle()
{
    if(p==NULL)
        p=new single;//如果p为空,就实例化d对象
    return p;
}

void single::releasesingle()
{
    delete p;
}

 main.cpp:

#include <iostream>
#include "single.h"
using namespace std;
//实例化单例出来
int main()
{
    single *p=single::makesignle();

    single *p1=single::makesignle();

    single::releasesingle();
    cout << "Hello World!" << endl;
    return 0;
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!