Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

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

I would like to check wether my 2d point and 3d points are identical using operator== that returns true if they are. How can I implement that? Do I need to add overloaded operator into both classes or what? How to compare 2 arguments x and y? My code:

#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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...