一、const修饰的变量,无法调用自身的非const修饰的成员函数
class A
{
public:
void setdata() ;
};
int main()
{
const A a;
a.setdata();
}
a.setdata(); 这句代码报错了:
//'this' argument to member function 'setdata' has type 'const A', but function is not marked const",
A对象被const修饰了,意思是A无法改变,A调用自身成员函数时,该函数必须被const修饰,否则该函数也有可能修改A中的成员变量,这是不允许的。因此报上面的错。
解决方法就是把A中的 void setdatd();
改为:
void setdatd() const;
二、非const左值引用类型 'type_xxx' 不能绑定到 'type_xxx' 类型的临时对象
class A
{
public:
void setStr(string &str);
string getStr()
{
return "";
}
};
int main()
{
A a;
a.setStr(a.getStr());//这句话报错了
}
a.setStr(a.getStr()); 此句会报错,信息如下:
"non-const lvalue reference to type 'basic_string<...>' cannot bind to a temporary of type 'basic_string<...>'"
"非const左值引用类型'basic_string<…>'不能绑定到basic_string<…>'类型的临时对象
由于setStr(string &str) 的形参为非const的,编译器认为有可能在setStr中修改str的值,然后因为a.getStr()会产生一个临时变量,临时变量一般认为是被const修饰的,因为临时变量用完就销毁了,所以临时变量一般不会被更改。所以这个报错的意思是,用一个const引用 传入到一个非const形参中,语义不符合。
(关于临时变量,可参考:关于c++中的临时变量_逍遥Fau的博客-CSDN博客_临时变量)
解决方案:
1、将setStr(string &str) 改为 setStr(const string &str)
2、修改调用方式为:
int main()
{
A a;
string myStr=a.getStr(); //创建出一个局部变量,不是临时变量了
a.setStr(myStr);
}
三、 static member function cannot have 'const' qualifier
class myClass
{
public:
static void func() const
};
原本一个普通类的成员函数,定义的时候,原先函数后面加了const修饰。后来把成员函数全部改成了static,就报了这个错误。
原因:
static成员函数不包含this
指针,static函数是属于类的,而不是某个实例,而const放在函数后面是用来修饰该函数的this指针,static函数后面跟const没有意义
换句话说:const成员函数用来修饰该成员函数的隐式this
指针为const型,而static成员函数不包含this指针。