基础知识:
(1)编译器会保证const修饰不可改变的约束
//tip 1:
char greeting[] = "Hello";
const char* p = greeting;
greeting[1] = 'x'; // wrong
p[1] = 'x'; // correct
//tip 2:
const char*p //表示被指物是常量
char* const p //表示指针自身是常量
(2)const对函数声明的应用
a. const修饰函数返回值
class Rational {...};
const Rational operator* (const Rational& lhs, const Rational& rhs);
Rational a, b, c;
(a * b) = c;//由于上述operator* 返回const,那么该错误的赋值会被编译器禁止
b. const成员函数
两个成员函数的常量性不同,可以被重载,如下例子:
class TextBlock {
public:
const char& operator[] (int pos) const
{ return text[pos]; }
char &operator[] (int pos)
{ return text[pos]; }
private:
string text;
}
注意:
a. 上面例子函数后面的const才支持重载,返回值的const不能支持重载
b. 如果函数返回值是的内置类型,而不是引用,那么
不能改动函数返回值,因此上面的operator[]返回应是引用,那么:
void testFunc(TextBlock& tb)
{
tb[0] = 'x'; //如果operator[]返回的不是引用,那么此处编译出错
}
(3)如果想在const成员函数中修改成员变量,那么在成员变量前使用mutable修饰
mutable int pos;
(4)在const和non-const成员函数中避免重复