您的位置:首页 > 编程语言 > C语言/C++

C++中的error C2662,const的this指针问题

2015-08-26 19:22 471 查看
今天在写C++代码的时候遇到一个错误,涉及到了常量的this指针的问题。

简化后的代码如下:

#include <iostream>
#include <string>
using namespace std;

class A
{
private:
string str;
string getStr();
public:
void print() const;
};

string A::getStr()
{
return str;
}
void A::print() const
{
cout << getStr() << endl;//error here
}

int main()
{
A a;
return 0;
}


这段代码在注释处会报编译错误如下:

error C2662: 'std::string A::getStr(void)' : cannot convert 'this' pointer from 'const A' to 'A &'


报错提示无法将this指针由“const A”类型转为“A &”类型。

几番查找下得知问题在于代码中的print()函数被声明了为const的,C++在调用类成员函数时会隐式的传递this指针,而将函数声明为const即相当于this指针被声明为const的,如下:

void print() const;


这个声明相当于:

void print(const A * this);


而这个被声明为const的this指针在print函数中调用getStr()时又会被传入,这里问题就出现了,getStr()函数并没有被声明为const的,那么这里面进行参数传递的时候就会发生类型不匹配的问题,也就是这里报的错误。

这里要清楚就是this指针的隐式传递,否则看到print()函数和getStr()函数都没有参数传递却报了这个错误就会感到莫名其妙,这也是我纠结了半天的问题。

解决的方法也很简单,将getStr()函数也声明为const的就可以了。

string getStr() const;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: