【发布时间】:2012-02-09 20:53:13
【问题描述】:
所以我一直被告知,良好的编码实践是使用访问器方法而不是直接访问成员变量,但是在编写重载运算符时,如果在运算符类定义中使用这些访问器方法,我将无法编译。所以假设以下类:
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;
}
但是,以下编译错误:
Point.cpp:7:36: 错误:将 'const Point {aka const Point}' 作为 'ushort Point::GetX()' 的 'this' 参数传递会丢弃限定符 [-fpermissive]
Point.cpp:8:36: 错误:将 'const Point {aka const Point}' 作为 'ushort Point::GetY()' 的 'this' 参数传递会丢弃限定符 [-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'关键字,后面的代码将编译,我不完全理解,只是因为我传入了一个 const 变量,为什么这会消除我使用访问器的能力方法?
【问题讨论】:
-
您的成员
operator+也应该是const合格的。您没有修改 this 参数。
标签: c++ methods operators overloading accessor