C++中的声明和定义的区别
2011-09-16 23:33
225 查看
声明:向计算机介绍名字
定义:分配存储空间
对于一个变量,仅声明,而不定义,必须符合两个条件:一、使用extern;二、不能赋值给变量赋值。
外部变量的定义只能有一次(因为只用进行一次分配内存空间),声明可以多次,声明的作用,只是表明该变量是一个已在后面定义过的外部变量
static声明一个变量:
(1)对于局部变量,则为该变量分配的空间在整个程序的执行期内都始终存在
(2)外部变量用static来声明,则该变量的作用只限于本文件模块
除了上面说的一些特征外,我觉得以下几点可以作为判断的依据:
是否实例化,能否使用,是否占用内存(分配了内存给它),
all
but one of the following are definitions:
int a; // defines
a
extern const int c = 1; // defines
c
int f(int x)
{ return x+a;
} // defines
f and defines x
struct S
{ int a; int b;
}; // defines
S, S::a, and S::b
struct X
{ // defines
X
int x; // defines
nonstatic data member x
static int y; // declares
static data member y
X():
x(0)
{ } // defines
a constructor of X
};
int X::y = 1; // defines
X::y
enum {
up, down }; // defines
up and down
namespace N
{ int d;
} // definesN
and N::d
namespace N1 = N; // defines
N1
X
anX; // defines
anX
whereas
these are just declarations:
extern int a; // declares
a
extern const int c; // declares
c
int f(int); // declares
f
struct S; // declares
S
typedef int Int; // declares
Int
extern X
anotherX; // declares
anotherX
using N::d; // declares
N::d
定义:分配存储空间
定义 | 声明 | |
变量 | 常规写法,如 int a | 加extern |
函数 | 包含函数体 | 不包含函数体(可加也可不加extern) |
外部变量的定义只能有一次(因为只用进行一次分配内存空间),声明可以多次,声明的作用,只是表明该变量是一个已在后面定义过的外部变量
static声明一个变量:
(1)对于局部变量,则为该变量分配的空间在整个程序的执行期内都始终存在
(2)外部变量用static来声明,则该变量的作用只限于本文件模块
除了上面说的一些特征外,我觉得以下几点可以作为判断的依据:
是否实例化,能否使用,是否占用内存(分配了内存给它),
all
but one of the following are definitions:
int a; // defines
a
extern const int c = 1; // defines
c
int f(int x)
{ return x+a;
} // defines
f and defines x
struct S
{ int a; int b;
}; // defines
S, S::a, and S::b
struct X
{ // defines
X
int x; // defines
nonstatic data member x
static int y; // declares
static data member y
X():
x(0)
{ } // defines
a constructor of X
};
int X::y = 1; // defines
X::y
enum {
up, down }; // defines
up and down
namespace N
{ int d;
} // definesN
and N::d
namespace N1 = N; // defines
N1
X
anX; // defines
anX
whereas
these are just declarations:
extern int a; // declares
a
extern const int c; // declares
c
int f(int); // declares
f
struct S; // declares
S
typedef int Int; // declares
Int
extern X
anotherX; // declares
anotherX
using N::d; // declares
N::d
相关文章推荐