如何使用重载运算符==来检查C++中的2d点和3d点是否相同?

How to use overloaded operator== to check if 2d point and 3d point are identical in C++?

我想使用 operator== 检查我的 2d 点和 3d 点是否相同,如果它们是 returns 则为真。 我该如何实施? 我是否需要将重载运算符添加到 类 或什么? 如何比较 2 个参数 x 和 y? 我的代码:

#include <iostream>

using namespace std;

class Point2D {
public:
    Point2D();
//  ~Point2D();
    void SetX(double x);
    void SetY(double y);
    double GetX();
    double GetY();

    
protected:
    double m_x, m_y;
};
class Point3D :Point2D {
public:
    Point3D() :Point2D() { m_z = 0.0; };
protected:
    double m_z;
};
Point2D::Point2D() {
    m_x = 0.0;
    m_y = 0.0;
}

void Point2D::SetX(double x) {
    m_x = x;
}
void Point2D::SetY(double y) {
    m_y = y;
}
double Point2D::GetX() {
    return m_x;
}
double Point2D::GetY() {
    return m_y;
}

int main() {
    Point2D T;

    cout << T.GetX() << " " << T.GetX() << endl;

    return 0;
}

首先,您可能想要public继承:

class Point3D : public Point2D {
// ~~~~~~~~~~~~~^

一旦你有了它,你就可以依靠多态性来为你处理事情,并且只为 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);
}

您可以通过使您的函数进一步改进它 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();
}