c++ const

c++使用const是为了保护数据在使用中不会被修改。

介绍:常变量,常对象,常变量的指针,常对象的指针,常指针和常引用

常变量: const int a=1;

 

常对象: const Time t(1,1,1); // Time::Time(int h, int m, int s):hout(h), minute(m), second(s){}

    只能通过构造函数的参数初始化表对常数据成员进行初始化。

 

常变量的指针:  const int* ptr;

                 const int a = 1;

                 ptr = & a;

    注:const的位置在最左侧,它与类型名int紧连,表示指针变量ptr指向的int变量时常变量,不能通过ptr来改变其值。

 

常对象的指针:  const Time* ptr;

                 const Time t(1,1,1);

                 ptr = &t;

                 常对象指针常用于函数形参,目的是在保护形参指针指向的对象,使它在函数执行过程中不被修改。

      eg: void fun(const Time* t) {...}   // t指向的对象不能在函数执行中被修改。

        

常指针:  Time t(1,1,1);

             Time *const ptr = &t; // ptr不能再改变指向

             常指针也常用作函数形参,目的是不允许在函数执行过程中改变指针变量的值,使其始终指向原来的对象。

 

常引用:  void fun(const Time &t); //函数声明

              常引用往往用在函数形参,目的是不希望函数修改实参的值。

 

 

 

posted @ 2014-03-22 20:59  Jie Forest  阅读(181)  评论(0编辑  收藏  举报