const
来源:互联网 发布:知行结合爱国 编辑:程序博客网 时间:2024/05/22 03:20
const
const int a = 10;const int *a = &b; //*a不能被修改int const *p = &b; //*a不能被修改int *const p = &b; // a不能被修改const int * const p = &c; // both a and *a can not be modifiedextern const int var; //var的原型不一定是const,但在这里不能修改
Const member function usage
- Repeat the const keyword in the defination as well as the declaration.
int get_day() const;
int get_day() const { return day; }
- Function members that do not modify data should be declared const.
- Const member functions are safe for const objects.
不可修改的对象
#include <iostream>using namespace std;class A {private: int i;public: A():i(10){} void f(){cout << "f()" << endl;}//参数:A* this void f() const {cout << "f() const" << endl;}//参数:const A* this};int main(int argc, char const *argv[]){ const A a; A b; a.f(); b.f(); return 0; }
代码段的变量不可修改
#include <iostream>using namespace std;int main(int argc, char const *argv[]){ char *s = "hello world"; //Warning - conversion from string literal to 'char *' is deprecated,加上const可以去掉warning. cout << s << endl; printf("s's address : %p\n", s); printf("main : %p\n", main); s[0] = 'B'; cout << s << endl; return 0;}
Error: Bus error
Error是因为:”hello world”是存在代码段的,代码段是不可修改的。
0 0
- const
- const
- const
- CONST
- const
- const
- const
- const
- const
- const
- Const
- const
- const
- const
- CONST
- const
- const
- const
- 基金知识入门理解
- Android百分比布局支持库
- 必学高级SQL语句
- 基于物理渲染的基础理论
- 在Windows平台上安装Node.js及NPM模块管理
- const
- Android图片缓存
- php+redis
- NYOJ 654 喜欢玩warcraft的ltl (01背包常数优化)
- <Linux内核探秘>读书笔记
- 生活中的观察者模式——一壶水的故事
- android隐藏软键盘的方法
- 向OpenCV3.0中添加opencv_contrib插件中的新功能
- oracle与mysql数据库的区别