定义义后就不能被修改,所以定义时必须初始化:const std::string hi = "hello!";
const指针
指向 const 对象的 const 指针
从 const 成员函数返回 *this
在普通的非 const 成员函数中,this 的类型是一个指向类类型的 const 指针,可以改变 this 所指向的值,但不能改变 this 所保存的地址。
在 const 成员函数中,this 的类型是一个指向 const 类类型对象的 const 指针。既不能改变 this 所指向的对象,也不能改变 this 所保存的地址。
不能从 const 成员函数返回指向类对象的普通引用。const 成员函数只能返回 *this 作为一个 const 引用。
// file_1.cc int counter; // definition // file_2.cc extern int counter; // uses counter from file_1 ++counter; // increments counter defined in file_1
// file_1.cc // defines and initializes a const that is accessible to other files extern const int bufSize = fcn(); // file_2.cc extern const int bufSize; // uses bufSize from file_1,extern 标志着bufSize 是一个声明,所以没有初始化式 // uses bufSize defined in file_1 for (int index = 0; index != bufSize; ++index) // ...
Code3.const引用则可以绑定到不同但相关的类型的对象或绑定到右值
/*const 引用可以初始化为不同类型的对象或者初始化为右值,如字面值常量:*/ int i = 42; // legal for const references only const int &r = 42; const int &r2 = r + i; /*同样的初始化对于非 const 引用却是不合法的,而且会导致编译时错误。其原因非常微妙,值得解释一下。 观察将引用绑定到不同的类型时所发生的事情,最容易理解上述行为。假如我们编写*/ double dval = 3.14; const int &ri = dval; /*编译器会把这些代码转换成如以下形式的编码:*/ int temp = dval; const int &ri = temp; // create temporary int from the double // bind ri to that temporary /*如果 ri 不是 const,那么可以给 ri 赋一新值。这样做不会修改 dval,而是修改了 temp。期望对 ri 的赋值会修改 dval 的程序员会发现 dval 并没 89有被修改。仅允许 const 引用绑定到需要临时使用的值完全避免了这个问题,因为 const 引用是只读的。*/
Code4. 一个对象(或表达式)是不是常量表达式由它的数据类型和初始值共同决定
const int max_files = 20; // max_files是常量表达式 const int limit = max_files + 1; // limit是常量表达式 int staff_size = 27; // staff_size不是常量表达式 const int sz = get_size(); // sz不是常量表达式 /*尽管staff_size的初始值是个字面值常量,但由于它的数据类型只是一个普通int而非const int,所以它不属于常量表达式。另一方面,尽管sz本身是一个常量,但它的具体值直到运行时才能获取到,所以也不是常量表达式。*/
Code5.const 限定符既可以放在类型前也可以放在类型后
string s; typedef string *pstring; //下面三种声明是等价的 const pstring cstr1 = &s; pstring const cstr2 = &s; string *const cstr3 = &s;
原文:http://blog.csdn.net/liufei_learning/article/details/21219963