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
- c++:const 操作小结
- C中Const小结
- c++const小结
- const小结(C++)
- C++const 关键字小结
- C中const的 小结
- c / c++ const 用法小结
- c语言 const用法小结
- C/C++中const用法小结
- C/C++中const用法小结
- C#:readonly和const用法小结
- c语言const、volatile问题小结
- C/C++中const用法小结
- C 语言之 const、static小结
- C/C++中const用法小结
- C语言中的const和static小结
- C/C++中const用法小结
- C/C++中const用法小结
- Perl 处理时间的小技巧 strftime
- handler
- 剖析MFC多线程程序的同步机制
- 判断机器大小端问题
- java---TCP通信 总结
- C++ const 小结
- 怎样设置Windows 7远程桌面连接(含xp)
- Baseline Requirements for the Issuance and Management of Publicly-Trusted Certificates, v.1.1
- MySQL的mysqldump工具的基本用法
- delphi 多线程编程 总结(转自万一老师)
- 【Golang】【 Network programming with Go】 Templates(模版)
- Hadoop 集群运行测试代码(Hadoop 权威指南天气数据示例)
- 【转】GHOST操作图文教程
- 安卓虚拟机路径含中文字符配置解决方案