【转】C++ const用法 尽量使用const

http://www.cnblogs.com/xudong-bupt/p/3509567.htmlhtml

 

  C++ const 容许指定一个语义约束,编译器会强制实施这个约束,容许程序员告诉编译器某值是保持不变的。若是在编程中确实有某个值保持不变,就应该明确使用const,这样能够得到编译器的帮助。ios

1.const 修饰成员变量 程序员

复制代码
 1 #include<iostream>
 2 using namespace std;
 3 int main(){
 4     int a1=3;   ///non-const data
 5     const int a2=a1;    ///const data
 6 
 7     int * a3 = &a1;   ///non-const data,non-const pointer
 8     const int * a4 = &a1;   ///const data,non-const pointer
 9     int * const a5 = &a1;   ///non-const data,const pointer
10     int const * const a6 = &a1;   ///const data,const pointer
11     const int * const a7 = &a1;   ///const data,const pointer
12 
13     return 0;
14 }
复制代码

const修饰指针变量时:编程

  (1)只有一个const,若是const位于*左侧,表示指针所指数据是常量,不能经过解引用修改该数据;指针自己是变量,能够指向其余的内存单元。函数

  (2)只有一个const,若是const位于*右侧,表示指针自己是常量,不能指向其余内存地址;指针所指的数据能够经过解引用修改。spa

  (3)两个const,*左右各一个,表示指针和指针所指数据都不能修改。指针

2.const修饰函数参数code

  传递过来的参数在函数内不能够改变,与上面修饰变量时的性质同样。htm

void testModifyConst(const int _x) {
     _x=5;   ///编译出错
}

3.const修饰成员函数blog

(1)const修饰的成员函数不能修改任何的成员变量(mutable修饰的变量除外)

(2)const成员函数不能调用非onst成员函数,由于非const成员函数能够会修改为员变量

复制代码
 1 #include <iostream>
 2 using namespace std;
 3 class Point{
 4     public :
 5     Point(int _x):x(_x){}
 6 
 7     void testConstFunction(int _x) const{
 8 
 9         ///错误,在const成员函数中,不能修改任何类成员变量
10         x=_x;
11 
12         ///错误,const成员函数不能调用非onst成员函数,由于非const成员函数能够会修改为员变量
13         modify_x(_x);
14     }
15 
16     void modify_x(int _x){
17         x=_x;
18     }
19 
20     int x;
21 };
复制代码

 4.const修饰函数返回值

(1)指针传递

若是返回const data,non-const pointer,返回值也必须赋给const data,non-const pointer。由于指针指向的数据是常量不能修改。

复制代码
 1 const int * mallocA(){  ///const data,non-const pointer
 2     int *a=new int(2);
 3     return a;
 4 }
 5 
 6 int main()
 7 {
 8     const int *a = mallocA();
 9     ///int *b = mallocA();  ///编译错误
10     return 0;
11 }
复制代码

(2)值传递

 若是函数返回值采用“值传递方式”,因为函数会把返回值复制到外部临时的存储单元中,加const 修饰没有任何价值。因此,对于值传递来讲,加const没有太多意义。

因此:

  不要把函数int GetInt(void) 写成const int GetInt(void)。
  不要把函数A GetA(void) 写成const A GetA(void),其中A 为用户自定义的数据类型。

 

  在编程中要尽量多的使用const,这样能够得到编译器的帮助,以便写出健壮性的代码。

相关文章
相关标签/搜索