(一)const与指针:
char greeting[] = "HELLO";
char *p = greeting;
const char *p = greeting; //指针所指物不能改变
char* const p = greeting; //指针自身不能改变
const char* const p = greeting; //指针自身跟指针所指物都不能改变
(二) STL迭代器:
vector<int> vec;
const vector<int>::iterator iter1 = vec.begin();
*iter1 = 10;
++iter1; //错误!!!iter1是const,所以他自身不能改变
vector<int>::const_iterator iter2 = vec.begin();
*iter1 = 10; //错误!!!iter2是const_iterator,所以他所指的东西不能改变
++iter1;
(三)函数返回const
class Rational {...};
const Rational operator*(const Rational& lhs, const Rational& rhs);
如果不返回const,那么如果程序员误写错代码:
Rational a, b, c;
if(a * b = c) //<span style="color:#ff0000;">程序员其实是想写:if(a * b == c) </span>
这样的话编译器就不会报错了!!
所以说如果返回const,那么程序员这种由于笔误而产生的错误就会被编译器发现了!!
(四)
在const成员函数中如果想要改变成员变量,可以在声明成员变量之前加上:mutable 例如:
class CTextBlock {
public:
size_t length() const;
private:
char* pText;
mutable size_t textLength;
mutable bool lengthIsValid;
};
size_t CTextBlock::length() const {
if(!lengthIsValid) {
textLength = strlen(pText); //如果上面声明的时候没有mutable,那么编译器会报错!
lengthIsValid = true; //如果上面声明的时候没有mutable,那么编译器会报错!
}
return textLength;
}
(五)在 const 和 non-const 成员函数中避免重复:
运用const成员函数实现出其non-const孪生兄弟:
class TextBlock {
public:
...;
const char& operator[](size_t position) const {
...;
...;
...;
return text[position];
}
char& operator[](size_t position) {
return
const_castchar*>(
static_cast<const TextBlock&>(*this)
[position] //*this是TextBlock类型,先转化为const TextBlock&类型 //然后用它调用const成员函数。返回一个const char&
//最后再把const去掉,返回char&。用这种方法来避免代码重复!
);
}
};
但是千万不能令const版本调用non-const版本来避免重复! 因为这样的话,对象有可能被改动。
请记住:
(1)将某些东西声明为 const 可帮助编译器侦测出错误用法。 const可被施加于任何作用域内的对象、函数参数、函数返回类型、成员函数本体。
(2)编译器强制实施bitwise constness,但你编写程序时应该使用“概念上的常量性”。
(3)当const和non-const成员函数有着实质等价的实现时,令non-const版本调用const版本可避免代码重复。但是反过来不可以!因为那样的话有可能会改变对象,但是const成员函数里面是不允许改变对象的!