重载一元运算符

来源:互联网 发布:淘宝卖家推广方法 编辑:程序博客网 时间:2024/05/18 13:24

重载一元运算符

不像你所看到的到目前为止经营者,阳性(+),负(-)和逻辑非(!)经营者都是一元运算符,这意味着他们只能运行在一个操作数。因为这些运营商没有改变他们的操作数,我们将实施他们作为朋友函数。所有三个操作数都是以相同的方式实现

让我们看看我们如何操作我们先前的例子实现

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 somethingSimilarly, 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 equivalentPoint operator- (const Point &cPoint){    return Point(-cPoint.m_dX, -cPoint.m_dY, -cPoint.m_dZ);}// Return true if the point is set at the originbool operator! (const Point &cPoint){    return (cPoint.m_dX == 0.0 &&        cPoint.m_dY == 0.0 &&        cPoint.m_dZ == 0.0);}


0 0
原创粉丝点击