私は、アクセサーメソッドとメンバ変数を直接アクセスするのが良いコーディング方法であることを常に教えてきましたが、オーバーロードされた演算子を記述する際に、これらのアクセサーメソッドを演算子クラス定義内で使用するとコンパイルできません。だから、次のクラスを想定しています。オペレーターの定義ではオーバーロードされた演算子でアクセサメソッドを使用できますか?
class Point
{
public:
Point() {};
virtual ~Point() {};
// Accessor Methods
inline void SetX(ushort nX) { m_nX = nX; }
inline void SetY(ushort nY) { m_nY = nY; }
inline ushort GetX() { return m_nX; }
inline ushort GetY() { return m_nY; }
// Overloaded Operators
Point operator+(const Point& pnt);
private:
ushort m_nX, m_nY;
};
、次は完全に合法と思われるが、それは私が教えられていたものに反する:
Point Point::operator+(const Point& pnt)
{
Point myPoint;
myPoint.SetX(GetX() + pnt.m_nX);
myPoint.SetY(GetY() + pnt.m_nY);
return myPoint;
}
ただし、次のエラーでコンパイル:「CONST」キーワードがパラから削除された場合
Point.cpp:7:36: error: passing 'const Point {aka const Point}' as 'this' argument of 'ushort Point::GetX()' discards qualifiers [-fpermissive]
Point.cpp:8:36: error: passing 'const Point {aka const Point}' as 'this' argument of 'ushort Point::GetY()' discards qualifiers [-fpermissive]
Point Point::operator+(const Point& pnt)
{
Point myPoint;
myPoint.SetX(GetX() + pnt.GetX()); // Here I am trying to use accessor methods vs. member variables
myPoint.SetY(GetY() + pnt.GetY());
return myPoint;
}
後者のコードはコンパイルされます私は完全に理解していませんが、const変数を渡しているだけで、アクセサーメソッドを使用する能力がなくなったのはなぜですか?
あなたのメンバー 'operator +'も 'const'修飾されている必要があります。あなたはこの議論を修正していません。 – pmr