下面是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. 静态的全局变量(即,具有内部链接的全局变量)不可以在其他文件中再次声明
关于第三点,我们设计模式中的单例模式演示一下:
自动析构版的单例模式
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; // 定义