声明与定义

下面是msdn上的定义,很抱歉,我的翻译可能有些蹩脚。


Declaration(声明):
A declaration introduces names and their types into a program without necessarily defining an associated object or function. However, many declarations serve as definitions.
声明向程序介绍名和类型,而不必要的定义一个与之关联的对象或函数。但是,很多声明就是定义。
Definition(定义):
A definition provides information that allows the compiler to allocate memory for objects or generate code for functions.
定义提供一些允许编译器为对象分配内存或为函数产生代码的信息。


从上述定义中,我们应当看出以下几点:
1. 定义本身就是一种声明,而声明不一定是定义
2. 同一个对象或函数只能有一份,而声明则可能有多个


根据经验,个人总结出来几条需要知道的,当然可能还有不足,真心希望有人帮忙补足。
1. 局部变量的定义与声明是同时进行的。
2. 全局变量定义以后,如果其他文件需要引用,需要通过extern的方式声明它。
3. 类静态成员变量只能在类中声明,而不能在类内定义和初始化。
4. 静态的全局变量(即,具有内部链接的全局变量)不可以在其他文件中再次声明


关于第三点,我们设计模式中的单例模式演示一下:


需要手动析构的单例模式:

class CSingleton
{
private:
	CSingleton(){;}
	CSingleton *instance;
public:
	~CSingleton(){;}
	CSingleton *GetInstance()
	{
		if (instance == NULL)
		{
			instance = new CSingleton;
		}
		return instance;
	}
};
CSingleton *CSingleton::Instance = NULL;		// 定义与初始化

自动析构版的单例模式

class CSingleton
{
public:
	CSingleton *GetInstance()
	{
		if (instance == NULL)
		{
			instance = new CSingleton;
		}
		return instance;
	}
private:
	CSingleton(){;}
	CSingleton *instance;
	~CSingleton(){;}
	class CGarbon
	{
		~CGarbon()
		{
			if (CSingleton::instance)
			{
				delete CSingleton::instance;
				CSingleton::instance = NULL;
			}				
		}
	};
	static CGarbon garbon;				// 声明
};

CSingleton *CSingleton::Instance = NULL;		// 定义与初始化
CSingleton::CGarbon CSingleton::garbon;		// 定义




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值