const
来源:互联网 发布:卖家淘宝小二在线联系 编辑:程序博客网 时间:2024/05/29 19:52
const:它指定一个语义约束,编译器会强制实施这个约束。它告诉编译器和程序员它所指定的值是应该保持不变的。
int a = 5; int b = 6; const int * p = &a;//*p是const的 int * const q = &a;//指针q是const的 q = &b;//错误 *p = b;//错误 *q = b; p = &b;
const 出现在星号的左边表示被指物是常量,如果出现在右边表示指针本身是常量。
const int *p;int const * p;//这两行的意义是一样的都是*p是常量
当我们在自己的class中重载*(乘法)号时应把它声明为const的
const myclass operator*(const myclass& lhs, const myclass& rhs);
把重载*的返回值声明为const是为了避免以下错误
if( a*b = c)//把==误输入为=
因为声明为了const所以编译器在这里会报错。否则- -.
const成员函数
注意:两个成员函数如果只有常量性(const)不同,它们就可以被重载。
eg:
class textbook{public:const char& operator[](int position) const{ return text[position];}char& operator[](int position){ return text[position];}private: string text; }void print( const textbook & c)//{ std::cout<<c[0];//这里调用的就是const operator[]}
参考书籍:《Effective C++》
0 0
- const
- const
- const
- CONST
- const
- const
- const
- const
- const
- const
- Const
- const
- const
- const
- CONST
- const
- const
- const
- HDU 3308 LCIS
- c++11特性之std::thread--初识
- 【HDU5527 2015长春赛区A】【贪心 特判模拟】Too Rich 最多硬币数支付 因子思想 贪心打补丁
- 实验二 栈和队列的应用
- [git]git export like command
- const
- 移动端图片格式调研
- redis主从设置
- 【HDU5534 2015长春赛区H】【树上DP转完全背包】Partial Tree 不同度不同权对应最大树权
- 不同的场景使用不同的泛型通配符
- HDU 5538 House Building(2015ACM/ICPC亚洲区长春&&几何体表面积)
- 自己对于的理解Android的生命周期
- hdoj 5521 Meeting 【优先队列 dijkstra】
- 【LeetCode从零单刷】Game of Life