c++编程思想读书笔记 之 const使用

默认认const是内部连接,不必创建存储空间。如果定义为extern 则为该const变量创建内存空间。

明确定义为外部可引用的const : extern const int x =1;

指向 const 指针 const int* p   和  int const* p 是一样的  p是一指针 指向const int   指向的值是不可变的

const指针  int * const p = &n                                      p是一指针 指向int 的const指针 指针的指向不可变   但值是可变的

可以认为const先修饰它左边的运算符 如果它已经在最左边 则看它右边的运算符。像int const *p :const修饰的是int值,故这个指针所指向的值是只读的;又如 const int *p :const 已在最左边,直接找它右边的是int 所以解释和前面的一样。 int* const p:const修饰的是int* 所以它的意思是只读的指针,初始化时赋值,不能再改所指的变量。 

const int* const p =&n   或   int const * const p= &n     指向和指向的值都不可变

 

可以把一非const对像地址赋给一个const指针,但不建议把const对像的地址赋给一个非const指针。为说什么建议呢,因为是允许,但容易出错。

const int x =2;  int *p =&x  //不合法

int*p1 =(int*)&x  //合法 但不建议

与函数相关

如果const修饰的是参数  则在函数中不能修改参数的值

返回值是const类型时 对于内建数据类型貌似没什么用处,但对于引用类型或是用户自定义类型是有用的。函数返回const类型对像不可做为左值。 以下是测试代码:

 1 #include <iostream>
 2 
 3  
 4 
 5 using namespace std;
 6 
 7  
 8 
 9 void printtest(int x)
10 
11 {
12 
13     cout<<x++<<endl;
14 
15 }
16 
17 //To explain not allow
18 
19 //void printtest1(int const x)
20 
21 //{
22 
23 //    cout<<x++<<endl;
24 
25 //}
26 
27  
28 
29 void printtest2(int  *p)
30 
31 {
32 
33     cout<<++(*p)<<endl;
34 
35 }
36 
37 //To explain not allow
38 
39 //void printtest3(int const *p)
40 
41 //{
42 
43 //    cout<<++(*p)<<endl;
44 
45 //}
46 
47 //
48 
49 void printtest4(int* const p)
50 
51 {
52 
53     cout<<++(*p)<<endl;
54 
55     int test= 30;
56 
57     //p=&test;  illegal
58 
59  
60 
61 }
62 
63 int main()
64 
65 {
66 
67     int test1 =20 ;
68 
69     printtest4(&test1);
70 
71     return 0;
72 
73 }

 

类中的const  如果一个对像声明为const  则它调用的方法也要是cont . 如 void class_s::class_s fun() const; 要把const写在方法定义的后 花括号前

声明为const的的方法也不是完全不可以改对像的属性,可以使用((Class_name*)this)->attribname =n ;  or (const_cast<Class_name*>(this))->attribname = m; 当然也可以直接把属性设置为mutable类型,这样就可以直接在const的方法中更改这个属性。

posted @ 2017-09-14 13:39  xep  阅读(159)  评论(0)    收藏  举报