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++》