重载一元运算符
不像你所看到的到目前为止经营者,阳性(+),负(-)和逻辑非(!)经营者都是一元运算符,这意味着他们只能运行在一个操作数。因为这些运营商没有改变他们的操作数,我们将实施他们作为朋友函数。所有三个操作数都是以相同的方式实现。
让我们看看我们如何操作在仙班我们先前的例子实现:
class Cents
{
private:
int m_nCents;
public:
Cents(int nCents) { m_nCents = nCents; }
// Overload -cCents
friend Cents operator-(const Cents &cCents);
};
// note: this function is not a member function!
Cents operator-(const Cents &cCents)
{
return Cents(-cCents.m_nCents);
}这应该是非常简单的。我国重载负算子(-)以型美分一个参数,并返回一个值类型分。
这里的另一个例子。的!运营商往往是作为一个测试,如果事情的值设置为零的速记方法。例如,下面的示例将只执行如果NX是零:
如果(!NX)
// do something
Similarly, we can overload the ! operator to work similarly for a user-defined class:
class Point
{
private:
double m_dX, m_dY, m_dZ;
public:
Point(double dX=0.0, double dY=0.0, double dZ=0.0)
{
m_dX = dX;
m_dY = dY;
m_dZ = dZ;
}
// Convert a Point into it's negative equivalent
friend Point operator- (const Point &cPoint);
// Return true if the point is set at the origin
friend bool operator! (const Point &cPoint);
double GetX() { return m_dX; }
double GetY() { return m_dY; }
double GetZ() { return m_dZ; }
};
// Convert a Point into it's negative equivalent
Point operator- (const Point &cPoint)
{
return Point(-cPoint.m_dX, -cPoint.m_dY, -cPoint.m_dZ);
}
// Return true if the point is set at the origin
bool operator! (const Point &cPoint)
{
return (cPoint.m_dX == 0.0 &&
cPoint.m_dY == 0.0 &&
cPoint.m_dZ == 0.0);
}
2004

被折叠的 条评论
为什么被折叠?



