从父类调用基类重载运算符

时间:2015-08-19 05:31:30

标签: c++ inheritance operator-overloading

在以下简单结构中,p3继承自p2。

struct p2 {
    double x, y;
    p2(double x, double y) : x(x),y(y){}
    bool operator ==(const p2& b) const{ return x == b.x && y == b.y; }
    bool operator !=(const p2& b) const{ return !(*this == b); }
};

struct p3 : p2 {
    double z;
    p3(double x, double y, double z) : p2(x,y),z(z){}
    bool operator ==(const p3& b) const{ return x == b.x && y == b.y && z == b.z; }
    bool operator !=(const p3& b) const{ return !(*this == b); }
};

在p3的重载比较运算符中,如何通过从父类调用重载运算符来替换x == b.x && y == b.y部分?

2 个答案:

答案 0 :(得分:1)

bool operator==(const p3& b) const
{
    return p2::operator==(b) && z == b.z; 
    //     ~~~~~~~~~~~~~~~~^
} 

答案 1 :(得分:1)

只需在派生结构

中使用范围操作符::

所以在你的operator==()结构p3中看起来像这样:

bool operator==(const p3& b) const {
    return p2::operator==(b) && z == b.z;
}
相关问题