Chinaunix首页 | 论坛 | 博客
  • 博客访问: 219516
  • 博文数量: 56
  • 博客积分: 2325
  • 博客等级: 大尉
  • 技术积分: 560
  • 用 户 组: 普通用户
  • 注册时间: 2009-03-30 18:18
文章存档

2012年(7)

2011年(1)

2010年(2)

2009年(46)

我的朋友

分类: C/C++

2009-05-17 19:47:10

    c++中的const用处广泛,但十分零碎,现总结如下.
1.定义const对象
    const int i = 0; //ok
    int j = 100;
    const k = i; //ok
    必须在定义时初始化const对象.
    const 对象默认为文件的局部变量,如下:
    //file1.c
    int a;
    const int b = 100; //只能在file1.c中使用
    extern const int c = 100; //能在file2.c中使用 
  
    //file2.c
    extern int  a;
    ++a; //ok
    a= c;
    
    b的作用域默认在file1.c,a和c可在整个程序中使用。
2.const 引用
    int b = 100;
    const int &a = b;
  const引用指的是指向const对象的引用。而引用一旦定义,就不可更改。要注意区分。
  非const引用只可以绑定到同类型的对象
   int a = 100;
   double b;
   int &s = a; //ok
   int &t = b; //error
   int &t = 100; //error
  const引用可以绑定到不同但相关对象或绑定到右值;
   const int &t = b; //ok
     编译器做以下转换:
     int temp = b;
     const int &t = tem;
 
   const int &t = a + 20; //ok 
 
 3.const和指针
  
   const指针: int *const ptr;
   指向const对象的指针: const int *ptr;
   指向const对象的const指针: const int *const ptr;
  
   typedef string *ptr;
   const ptr p;
   问p的类型?
   const string *ptr; //wrong
   string *const ptr; //ok
 
   因为typedef新定义了一种类型,而非做了简单的文本扩展。p是const ptr类型。
4.类编写中的const
  (1). 函数形参
     当形参只读时,可将其设为const引用型。不但起到保护作用,同时扩展了可传入实参的范围。
     void func(const int &a);
 
     可传入相关对象或者右值。
  (2). const this
     当为类的成员函数时:   
     void func () const;
     表明this指针指向的是const对象。但const对象或非const对象皆可调用。若不加const,则const对象不可调用此函数。 
   
 
 
 
   
 
     
阅读(944) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~