C++ 单例模式实现代码
2016-03-12 14:48
513 查看
#pragma once
class singleton
{
public:
//static int a;
static singleton * getinstance()
{
if (!instance)
{
instance = new singleton();
}
return instance;
}
static void release()
{
if (!instance)
{
delete instance;
instance = NULL;
}
}
protected:
singleton()
{
//instance
}
static singleton* instance;
};
singleton* singleton::instance = NULL;
这句话一定要有。。。居然忘记类静态成员怎么初始化的。。。C++类静态数据成员要放在全局空间初始化。
// C++面向对象编程练习.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
#include "vector.h"
#include "singleton.h"
#include "singleton.cpp"
using namespace std;
int main()
{
//int a = singleton::a;
//test
singleton *s = singleton::getinstance();
singleton *s1 = singleton::getinstance();
if (s == s1)
{
cout << "YES"<< endl;
}
s->release();
return 0;
}
class singleton
{
public:
//static int a;
static singleton * getinstance()
{
if (!instance)
{
instance = new singleton();
}
return instance;
}
static void release()
{
if (!instance)
{
delete instance;
instance = NULL;
}
}
protected:
singleton()
{
//instance
}
static singleton* instance;
};
singleton* singleton::instance = NULL;
这句话一定要有。。。居然忘记类静态成员怎么初始化的。。。C++类静态数据成员要放在全局空间初始化。
// C++面向对象编程练习.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
#include "vector.h"
#include "singleton.h"
#include "singleton.cpp"
using namespace std;
int main()
{
//int a = singleton::a;
//test
singleton *s = singleton::getinstance();
singleton *s1 = singleton::getinstance();
if (s == s1)
{
cout << "YES"<< endl;
}
s->release();
return 0;
}
相关文章推荐
- C++开源库
- C++第一次上机报告 1-2
- C++11 lambda表达式
- c++第2次上机实验-1
- Thinking in c++ exercise 4-26 关于二维数组指针
- VC++ Excel电子表格读写示例
- c++ 实现动态顺序表(拷贝构造 赋值运算符重载等操作)
- c++ 写时拷贝
- c++ 深浅拷贝(传统写法 xain'dai'xie'fa)
- c语言常见50题 及答案(递归 循环 以及常见题目)
- C++实验1-三个整数输出最大值
- [变态的C++]“迷路”的函数调用错误
- 用C++实现顺序表
- Inputreader.cpp里virtualkey的流程
- C++ 友元类的学习与使用
- Dev C++初始化(默认)代码修改方法
- “位拷贝”和“值拷贝”的区别(c++)
- 【HPU】[1006]DNA
- 四则运算C语言程序
- C++ 通过友元函数对类进行iostream流重载