euphoriola

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

const是constant的缩写

constant[英][ˈkɔnstənt] [美][ˈkɑnstənt] 

adj.不断的,持续的;永恒的,始终如一的;坚定;忠实的

n.[数]常数,常量;不变的事物;永恒值

const是一个C语言的关键字,它限定一个变量不允许被改变。使用const在一定程度上可以提高程序的安全性和可靠性。


 

const用法


定义变量:

1 const int i = 10;

const改为外部连接,作用于扩大至全局,编译时会分配内存,并且可以不进行初始化,仅仅作为声明,编译器认为在程序其他地方进行了定义.

1 extend const int i = 10;

定义指针:

 1     int i = 50;
 2     int j = 100;
 3     const int* x = &i; //the value is const
 4     x = &j;
 5     *x = 99; //compile error
 6     int* const y = &i; //the pointer is const
 7     *y = 99;
 8     y = &j; //compile error
 9 
10     const int* const xy = &i;//both of the pointer and the value is const

 函数中的const:

用const修饰函数参数,则其在函数体内不可被改变,否则编译器报错

1     void foo(const int i) {
2         i = 10; //compile error
3     }

用const修饰函数的返回值,那么函数返回值的内容不能被修改,且该返回值只能被赋给用const修饰的同类型变量。例如:

1 const char * GetString(void);
2 
3 char *str = GetString(); //compile error
4 
5 const char *str = GetString();

 


 

 

const在类中的应用

 

(1)const修饰成员变量
const修饰类的成员函数,表示成员变量只读,不能被修改,同时它只能在初始化列表中赋值。

(2)const修饰成员函数
const
修饰类的成员函数,则该成员函数不能使用类中任何非const成员函数,不能修改类中的任何成员变量。一般写在函数的最后来修饰。

 1 class A
 2 {
 3 public:
 4     A(int i): x(i), y(0) { 
 5         x = 1; //compile error
 6     }
 7 
 8     void hello() {
 9         cout<<"hello"<<endl;
10     }
11 
12     void func() const {
13         hello(); //compile error
14         cout<<"const func"<<endl;
15     }
16 
17 public:
18     const int x;
19     int y;
20 };

 (3)const修饰类对象/对象指针/对象引用

 1     const A a(0);
 2     a.hello(); //compile error
 3     a.func();
 4 
 5     const A* pa = new A(0);
 6     pa->hello(); //compile error
 7     pa->func();
 8 
 9     A* const paa = new A(0);
10     paa->hello();
11     paa->func();

 


 

 

const与static的区别

 

 static是静态,面向全局,分配在数据区(data segment

const是只读,面向局部/对象,分配在栈区(stack segment

 

 

 

 

posted on 2013-11-04 16:23  euphoriola  阅读(227)  评论(0)    收藏  举报