C++ 实际项目中设置全局变量三种方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xin_y/article/details/86311293

#include<iostream>
using namespace std;
#include<stdlib.h>
#include<stdio.h>

/** method one *****/

template<typename T>
class Singleton
{
	public:
		static T& Instance()
		{
			if(s_Instance == 0)
			{
				s_Instance = new(T)();
				atexit(Destroy);
			}
			return *s_Instance;
		}
	protected:
		Singleton() {}
		virtual ~Singleton() {}
	private:
		static void Destroy()
		{
			if(s_Instance != 0)
			{
				delete(s_Instance);
				s_Instance = 0;
			}
		}
		static T* volatile s_Instance;
};

template<typename T>
T* volatile Singleton<T>::s_Instance = 0;

class Example : public Singleton<Example>
{
	public:
		void get() { printf("method one\n");}
};

/** method two *****/

class Example1
{
	public:
		void get() { printf("method two\n");}

};

Example1 e2;

/** method three *****/
class Example2
{
	public:
		static Example2& Instance()
		{
			static Example2 e;
			return e;
		}

		void get() { printf("method three\n");}


};
#define EXAMPLE() Example2::Instance()

//-------------------------


int main()
{
	Example e1 = Example::Instance();
	e1.get();

	e2.get();

	EXAMPLE().get();
	

	return 0;
}

猜你喜欢

转载自blog.csdn.net/xin_y/article/details/86311293