const修饰的对象,该对象的任何非const成员函数都不能被调用,因为任何非const成员函数会有修改
成员变量的企图。
class AAA
{
public:
void func1();
void func2() const;
void func3(const string &str)
{
str.at(0)
str.clear();
};
};
const AAA *a = new AAA;
a->func1();//错误
编译会报:error C2662: “AAA::func1”: 不能将“this”指针从“const AAA”转为“AAA &”
a->func2();//正确
作为参数调用时的情况:
AAA a;
string str = "aaa";
a.func3(str);
str.at(0)//正确
str.clear();//错误
error C2662: “std::basic_string<_Elem,_Traits,_Alloc>::clear”: 不能将“this”指
针从“const std::string”转换为“std::basic_string<_Elem,_Traits,_Alloc>
参考:
http://www.cnblogs.com/lichkingct/archive/2009/04/21/1440848.html