-
const 出现在*左边,表示被指物是常量,出现在*右边,表示指针自身是常量。
-
迭代器中的const:
1)const_iterator的作用为:const T* 和T const *
2)const std::vector<int>::iterator iter;
等同于:T* const -
const修饰返回值的作用是防止返回值被错误的赋值,如:
class Rational{...};
const Rational operator*(const Rational& lhs,const Rational& rhs);
Rational a,b,c;
if(a * b = c)...
- const 成员函数:const修饰成员函数是为了确定该成员函数可作用于const对象上。
1)重载要求函数参数的个数、类型、顺序不同,不能只有返回值不同。而成员函数通过const修饰,也可以形成函数重载。
class TextBlock{
//下面两个函数是重载
const char& operator[](std::size_t position) const {
return text[position];
}
char& operator[](std::size_t position){
return text[position];
}
private:
std::string text;
};
2)编译器强制实施bitwise constness,但你编写程序时应该使用“概念上的常量性”(conceptual constness)
- 位常量/物理常量(bitwise constness/physical constness):const成员函数不改变对象内的任何一位。编译器遵循位常量。
位常量的问题:若对象内有指针成员,虽然const成员函数没有改变对象内的成员,但却可以改变指针所指向的内容。因此位常量能保证物理上的位常量性,无法保证逻辑上的常量性。
- 逻辑常量(logical constness):const成员函数可以改变对象的某些位,只有在客户端侦测不出的情况下才得如此。
逻辑常量性的问题:允许成员函数改变对象中的某些位,但需要通过将对象中的成员变量加mutable修饰才可以,否则无法通过编译。
3)当const和non-const成员函数有着实质等价的实现时,令non-const版本调用const版本可以避免代码重复