随笔 - 8  文章 - 26  trackbacks - 0
<2024年7月>
30123456
78910111213
14151617181920
21222324252627
28293031123
45678910

常用链接

留言簿(4)

随笔档案

文章分类

文章档案

相册

C++语言

搜索

  •  

最新评论

阅读排行榜

评论排行榜

 

1.       const int r=100; //标准const变量声明加初始化,因为默认内部连接所以必须被初始化,其作用域为此文件,编译器经过类型检查后直接用100在编译时替换

 

2.const修饰指针

第一种情况:const int *ptr=&a; ptr为指向常量的指针,其所指的值不可修改,但是其所指向的地址可以修改。

第二种情况:int * const ptr=&aptr为常量指针,其所指的地址不可被修改,但是其所指的值可以被修改。

第三种情况:const int * const ptr=&aptr为指向常量的常量指针,其所指向的地址不可修改,其所指向的值也不可修改。

实例:
 1#include <iostream>
 2using namespace std ;
 3
 4int main()
 5{
 6
 7    int a=1;
 8    int b=2;
 9    int c=3;
10    int d=4;
11
12
13    //第一种情况:
14    const int * ptr_one=&a;
15
16    // *ptr_one=3; 错误ptr为指向常量的指针,其所指的值不能修改
17
18    ptr_one=&b;//正确,ptr所指向的地址可以修改
19
20
21    //第二种情况:
22    int *const ptr_two=&c;
23
24    //ptr_two=&d;//错误,ptr_two为常量指针,其所指的地址不可修改
25
26    *ptr_two=4;//正确,prt_two所指向的值可以修改
27
28
29    //第三种情况:
30    const int * const ptr_three=&a;
31
32    //*ptr_three=5; 错误:ptr_three为指向常量的常量指针,其所指向的值不可修改
33
34    //ptr_three=&b;  错误:ptr_three所指向的地址不可修改
35
36
37}

3.const 用于函数参数
直接看实例:

 1void fun_one(const int * r)
 2{
 3
 4//*r=1;//错误,不能在函数内改变r所指向的值
 5
 6}

 7
 8void fun_two(int * const r)
 9{
10
11//r=new int(1);//错误,不能改变r所指向的地址
12
13}

14
15void fun_three(const int r)
16{
17
18//r=1;//错误,不能改变r的值
19
20}
 

4.const 对于类

{1}对于const 修饰的类成员变量,只能在构造函数的参数初始化表里对其进行初始化,否则会引起编译错误。

2)对于const 修饰的成员函数 ,如 int Funint aconst,这样声明之后任何企图在函数内部修改成员变量的值或者调用非const成员函数都会引起编译错误。

3)对于const声明的用户自定义类的对象,如果调用这个类的非const成员函数,将会引起编译错误,编译器会保证在const对象的生命期内不被改变。

如果const对象一定要调用此函数的话,那就将此函数声明为const
实例:

 1#include <iostream>
 2using namespace std ;
 3
 4class Test
 5{
 6public:
 7    
 8    Test():const_value(0)
 9    {
10        value=0;
11    }

12
13    
14
15    Test(int i,int m):const_value(m)
16    {
17        value=i;
18    }

19
20void    PrintValue() const
21    {
22    cout<<"\nValue的值为:"<<value;
23    
24    }

25
26private:
27    int value;
28    const int const_value;
29
30}
;
31
32
33int main()
34{
35
36Test a(5,5);
37a.PrintValue();
38
39const Test b(6,6);
40b.PrintValue();
41
42}


posted on 2008-06-27 22:16 杨彬彬 阅读(135) 评论(0)  编辑 收藏 引用 所属分类: C++语言

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理