在C++中const用来对目标的性质进行相应的限制,使用const修饰后,不能对目标内容进行修改。特别是当const修饰成员函数的时候,对函数的使用有相应的限制。一般来说,const对象只能调用const成员函数,如果const对象需要调用非const成员函数则需要使用使用mutable修饰变量或者使用this指针进行强制类型转换,而非const对象则可以调用const成员函数以及非const成员函数,但是优先使用非const成员函数。
例如如下代码中:
#include <iostream>
using namespace std;
class test
{
private:
string str;
public:
char& operator[](const size_t index)
{
cout << "no_const" << endl;
return str.at(index);
}
const char& operator[](const size_t index) const
{
cout << "const" << endl;
return str.at(index);
}
test(string str1):str(str1){}
};
int main()
{
test str1("hello world");
cout << str1[2] << endl;
const test str2("hello world");
cout << str2[2];
return 0;
}
输出结果为:
no_const
l
const
l
可见在调用成员函数时,const对象调用了const类型成员函数,非const对象调用非const成员函数。
如果类定义中的非const成员函数删除,那么非const对象将调用const成员函数,可见,非const对象优先选择非const成员函数。
在判断const的修饰对象时,可使用一个简单的规则:如果const位于*号的左面,则const修饰的是指针指向的变量,如果const位于*号的右面,则const修饰的是指针,如果两边都有的话这变量和指针均是常量