如何使用重载运算符==来检查C++中的二维点和三维点是否相同



我想使用运算符==检查我的二维点和三维点是否相同,如果是,则返回true。我该如何实现?我需要在两个类中都添加重载运算符吗?如何比较两个参数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;
}

首先,您可能想要公共继承:

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();
}

最新更新