1. 程式人生 > >error C2662: 無法將this指標從const轉化為非const

error C2662: 無法將this指標從const轉化為非const

今天在寫程式時遇到了一個報錯:

error C2662: 'x' : cannot convert 'this' pointer from 'const class Point3d' to 'class Point3d &'

先看下程式碼:

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;

class Point3d
{
public:
 Point3d(int x = 0, int y = 0, int z = 0):m_x(x), m_y(y), m_z(z){}
public:
 int x() {return m_x;}
 int y() {return m_y;}
 int z() {return m_z;}
 void X(int x){m_x = x;}
 void Y(int y){m_y = y;}
 void Z(int z){m_z = z;}
private:
 int m_x;
 int m_y;
 int m_z;
};
inline ostream& operator<<(ostream &os, const Point3d &pd)
{
 return os << " m_x: " << pd.x() << " m_y: " << pd.y() << " m_z: " << pd.z();


}

報錯點是標紅的這一行,分析了半天,找不到問題的原因.

然後回到報錯資訊的提示,看看能不能找到些許的蛛絲馬跡:無法將this指標從const引用類物件型別轉換為類物件型別,再把這個錯誤翻譯一下:就是報錯的原因在於我們將一個const this指標轉換為一個非const導致的錯誤。

那麼這是為什麼呢?回到程式碼,我們在過載<<函式中聲名的第二個引數是一個const Point3d& 類物件的引用,而在函式實現內部,我們用其呼叫類的成員方法x(),這裡發生了什麼?沒錯,這裡編譯器隱含了一個const this指標傳給了類成員函式x(),而在類的實現中這個成員函式是非const的,這個函式的隱含this指標引數是非const的.換句換說,這個函式形參與實參結合時,發生了const 指標到非const指標的轉換,因此報錯!!!

知道了報錯原因,我們把類的這些成員函式宣告為const,函式宣告為const,隱含的this指標也變成了const,於是這個問題應該不會再發生了

// C++中實現

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
class Point3d
{
public:
 Point3d(int x = 0, int y = 0, int z = 0):m_x(x), m_y(y), m_z(z){}
public:
 int x() const{return m_x;}
 int y() const{return m_y;}
 int z() const{return m_z;}
 void X(int x){m_x = x;}
 void Y(int y){m_y = y;}
 void Z(int z){m_z = z;}
// inline ostream& operator<<(ostream &os/*, const Point3d& pd*/)
/* {
  return os << " m_x: " << this->X() << " m_y: " << this->Y() << " m_z: " << this->Z();
 }*/
private:
 int m_x;
 int m_y;
 int m_z;
};
inline ostream& operator<<(ostream &os, const Point3d &pd)
{
 return os << " m_x: " << pd.x() << " m_y: " << pd.y() << " m_z: " << pd.z();
}

重新編譯,Ok!!!

編譯環境:VC++6.0