首页 / 软件开发 / C++ / 《Effective C++》读书笔记03:多才多艺的const
《Effective C++》读书笔记03:多才多艺的const2011-04-06 博客园 月光笛手const是我们写c++代码时的常客,对于那些我们不希望修改的对象,最好用const进行 修饰。1.下面来看看一些惯用法:1 char greeting[] = "Hello";
2 char* p = greeting; //非const指针,非const数据
3 const char* p = greeting; //非const指针,const数据
4 char const *p = greeting; //非const指针,const数据
5 char* const p = greeting; //const指针,非const数据
6 const char* const p = greeting; //const指针,const数据
3和4行虽然形式不同,不过功能是类似的。3和5有本质的不同,可以这么理解:const会修饰在它后面所有的代码,比如第3,4中 的const修饰char* p,表示char*,而在第5中const修饰p,表示指针。可这些在STL中有所不同,由于iterator是一个指针,用const修饰一个iterator会类 似于上面第3行,而如果要产生第5行的效果,需要使用const_iterator:1 using namespace std;
2
3 vector<int> vec;
4 const vector<int>::iterator iter = vec.begin();//类似于T* const
5 *iter = 10; //正确,可以修改iter所指的值
6 ++iter; //错误,iter是const
7
8 vector<int>::const_iterator cIter = vec.begin();//类似于const T*
9 *cIter = 10; //错误,cIter指向的值是const
10 ++cIter; //正确
总结一下:在一般的应用中const会修饰其后的变量和修饰符,而只有在STL的 iterator中,const iterator==T* const;const_iterator==const T*。记住,尽可能地将不能修改的变量声明为const!2.在成员函数中使用const时,如果将成员函数声明为const,则函数中任何对任何成 员变量进行修改都会导致错误,这样可以防止我们对对象无意的修改1 class TestBlock
2 {
3 public:
4 void ConstFunc() const;//const函数
5 private:
6 char* text;
7 int size;
8 bool isValid;
9 }
10
11 void TestBlock::ConstFunc() const
12 {
13 if(!isValid)
14 {
15 size = strlen(text);//错误
16 isValid = true;//错误
17 }
18 }
可以通过将成员变量声明为mutable(可变的)来消除这种错误1 mutable int size;
2 mutable bool isValid;
3
3.const可用于重载,如果两个函数参数完全一致,可以通过将返回值声明为const或 将函数声明为const来进行重载,不过在实现的时候,可以用非const函数来调用const函 数,从而减少代码重复。这一块感觉用不太多,暂时就不管了。