C++中的error C2662,const的this指針問題


今天在寫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;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM