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