现在的位置: 首页 > 综合 > 正文

c++声明/定义,静态/非静态,变量/函数

2013年04月20日 ⁄ 综合 ⁄ 共 1255字 ⁄ 字号 评论关闭

我以前也很糊涂,所以研究了一下,写了一个例子。如下

 

//----------------- def.h ----------------

#ifndef _DEF_H_
#define _DEF_H_

static int a = 1;
extern int b;
int add();

#endif

 

//---------------- def.cpp ---------------

#include "def.h"
#include <iostream>

static int c = 4;

int add()
{
    a = a + b + c;
    return a;
}

int print()
{
    printf("a:%d/n",a);
}

 

//-------------- main.cpp ----------------

#include "def.h"
#include <iostream>

int b = 2;
extern int c;

int print();

int main()
{
    printf("a:%d/n",a);
    printf("b:%d/n",b);
//    printf("%d/n",c);
    printf("add:%d/n",add());
    printf("a:%d/n",a);
    print();
}

 

//----------------- 结果 --------------------

a:1
b:2
add:7
a:1
a:7

 

逐一说明一下:

 

声明和定义

 

函数的申明和定义很容易区分,如下

int add(); //是声明

int add(){} //是定义

类中的方法声明和定义和函数的也是一样的。

 

变量的声明和定义比较容易晕。

int b = 2;  //声明和定义

extern int b; //定义

 

关于声明和定义,不管是变量和函数,都可以先在头文件中声明,然后在某一个cpp文件中定义。在其他的cpp文件中使用;也可以不在头文件中声明,在每个使用的cpp文件中声明。

 

静态和非静态

1.静态和非静态主要区别在于生存周期,静态是和程序声明周期一样的,非静态是和函数或者文件声明周期一样的;

2.静态和非静态另外一个区别就是作用范围,比如全局变量静态的作用范围是文件(include引用了,也可以用,比如a文件定义的静态全局变量,b文件引用了a文件,b中是可以用的),而非静态的全局变量作用范围是整个程序。

    a.可以看例子中的static int a = 1;虽然在def.cpp和main.cpp中都可以使用,但是调用add之后,a在def.cpp中已经变为7,但是在main.cpp中a仍让是1。

    b.可以参考static int c = 4;,是在def.cpp中声明和定义的,在main.cpp中,如果extern int c;在printf("%d/n",c);这句,编译时提示c未定义。也就是说def.cpp中定义的静态变量,在main.cpp中是找不到的。

 

定义公共参数时c的定义方法是#define FLAG 1,但是c++中建议static const int FLAG=1;这是全局静态的常量。

抱歉!评论已关闭.