C++ 的 声明&定义&初始化

在C++和Java中,我们在使用一个标识符之前必须对它进行声明。标识符的声明和标识符的定义并不是一回事(虽然绝大数情况下它们看起来并没有什么不同)。
在声明中,除非我们为一个标识符分配了足够的内存,否则这个标识符便没有被定义。
另外,当一个标识符作为一个变量的名称时,我们还将面临的一个问题是,这个变量在定义之时是否得到了缺省的初始值。

所以判定一条语句时候,可以用这个规则:
是否声明-->声明后是否定义(有无分配内存)-->定义后是否缺省初始化(有无初始化0)


下面用我自己写的一个很简单的例子来说明三者之间的关系:
#include <iostream>

using namespace std;

//author:snail
//date:070402

class small{
    public:
        int classVar[10];//[declare]        [define    ]       [not defaylt init!]
        static int arrayVar[10];
        static int classStaticName;//[declare]        [not define]        [not init]
        static int getValue(){return classStaticName;}
};

int small::classStaticName = 1;//class static member must init here!

int small::arrayVar[10] = {1};

int globleVar[10];//[declare]     [define]        [default init]

int main(){
    int methodVar[10];//[declare]     [define]         [not init!]
    static int methodStaticVar[10];//[declare]     [define]        [init!]
    small s;
   
    cout << "globleVar[0] " << globleVar[0] << endl;
    cout << "globleVar[1] " << globleVar[1] << endl;
    cout << "s.classVar[0] " << s.classVar[0] << endl;
    cout << "s.classVar[1] " << s.classVar[1] << endl;
    cout << "small::arrayVar[0] "<< small::arrayVar[0] << endl;
    cout << "small::arrayVar[1] "<< small::arrayVar[1] << endl;
    cout << "small::getValue() " << small::getValue() << endl;
    cout << "small::classStaticName " << small::classStaticName << endl;
    cout << "methodVar[0] " << methodVar[0] << endl;
    cout << "methodVar[1] " << methodVar[1] << endl;
    cout << "methodStaticVar[0] " << methodStaticVar[0] << endl;
    cout << "methodStaticVar[1] " << methodStaticVar[1] << endl;
   
    return 0;
}


输出结果:
globleVar[0] 0            //全局变量 在int globleVar[10];    声明+定义+缺省初始化
globleVar[1] 0  
s.classVar[0] 6204724    //类的非静态成员变量 int classVar[10];   声明+定义+(未缺省初始化)
s.classVar[1] -1208501944
small::arrayVar[0] 0       //类的静态成员变量 static int arrayVar[10]; 声明 + (未定义) + (未缺省初始化),所以必须有另一条语句int small::arrayVar[10] = {1} 定义 + 初始化 !!!
small::arrayVar[1] 0     
small::getValue() 1
small::classStaticName 1
methodVar[0] 134515496   //函数局部变量 int methodVar[10];//[declare];声明+定义+(未缺省初始化)
methodVar[1] 134516988
methodStaticVar[0] 0      //函数静态局部变量 static int methodStaticVar[10]; 声明+定义+缺省初始化
methodStaticVar[1] 0


下列的声明也不是定义:
extern int error_name;    //外部变量
class Student;            //照顾编译器"向前看"的特点
double d(double);         //照顾编译器"向前看"的特点

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值