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

本文详细介绍了在实际C++项目中设置全局变量的三种方法,包括静态全局变量、外部链接全局变量和使用命名空间的方式。通过实例解析,帮助开发者理解不同方法的应用场景及优缺点。
摘要由CSDN通过智能技术生成

#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;
}

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值