C++ const 小结

来源:互联网 发布:蓝天准系统知乎 编辑:程序博客网 时间:2024/05/19 23:14

声明常量

const int i = 10;// 常用int const i = 10;// 不常用const int i;// 错误
1 和 2 意思一样,都是 i 的值不可修改。


修饰指针

const int *p;// 常用int * const p;// 不常用
第一种:p 指向的变量的的值不可修改。

You can think of this as reading that *p is a "const int". So the pointer may be changeable, but you definitely can't touch what p points to.


第二种:p 的指向不能变。

The way to think about it is that "* const p" is a regular integer, and that the value stored in p itself cannot change--so you just can't change the address pointed to.


返回值为 const 型指针

意义跟声明指针变量时一致,如:

const FileDescriptor* FindFileByName(const string& name);


修饰引用

int a; // or: int a = 100;const int &refer = a;
含义同 const int *p


与类相关的 const——修饰成员变量

两种方式:一是声明成员时初始化,必须加 static 修饰;二是用初始化列表,

static

#include <iostream>using namespace std;class CTest{public:static const int a = 99;};int main(int argc, char const *argv[]){CTest test;cout << test.a << endl;cout << CTest::a << endl;// 访问方式和 Java 不太一样return 0;}

初始化列表

#include <iostream>using namespace std;class CTest{public:CTest(int aa): a(aa) {}CTest(): a(99) {}public:const int a;};int main(int argc, char const *argv[]){CTest test1(9);CTest test2;cout << test1.a << endl;cout << test2.a << endl;return 0;}


与类相关的 const——const 型成员函数

class LIBPROTOBUF_EXPORT Descriptor {...const FileDescriptor* FindFileByName(const string& name) const;...}

a. const 成员函数不能修改类中任何数据成员。这种写法的好处除了保护数据成员外,还有一个好处是可读性好,使用者一看就知道这个函数不修改数据成员。

b. 依照规则 a, const 成员函数中不能调用非 const 成员函数。

注意:非 const 成员函数是可以访问 const 成员变量的,网上有些文章简直就是胡扯。


与类相关的 const——const 对象

const 对象中的任何数据成员是不能修改的,相应地,不能调用 const 对象的非 const 成员函数。


理解 const 的例子

http://blog.csdn.net/duyiwuer2009/article/details/15683625

这个例子可以更好地理解与类相关的 const.


References

The.C++.Programming.Language.3rd.Edition

Const Correctness, http://www.cprogramming.com/tutorial/const_correctness.html