C++,error c2662 cannot convert 'this' pointer from 'const A' to 'A &'

天在写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;
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值