First, you probably want public inheritance:
class Point3D : public Point2D {
// ~~~~~~~~~~~~~^
Once you have that, you can rely on polymorphism to handle things for you and only implement comparison operator for Point2D
:
// the arguments should be const, but your classes are not const correct
bool operator== (/*const*/ Point2D& lhs, /*const*/ Point2D& rhs)
{
return lhs.GetX() == rhs.GetX() && lhs.GetY() == rhs.GetY();
}
int main() {
Point2D p2;
Point3D p3;
std::cout << std::boolalpha << (p2 == p3);
}
You can further improve it by making your functions const
:
class Point2D {
public:
Point2D();
void SetX(double x);
void SetY(double y);
double GetX() const; //here
double GetY() const; //here
protected:
double m_x, m_y;
};
double Point2D::GetX() const { //and here
return m_x;
}
double Point2D::GetY() const { //and here
return m_y;
}
//now you can pass arguments by const reference, no accidental modifications in the operator
bool operator== (const Point2D& lhs, const Point2D& rhs)
{
return lhs.GetX() == rhs.GetX() && lhs.GetY() == rhs.GetY();
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…