温馨提示×

能否用C++的point类实现坐标操作

c++
小樊
81
2024-09-25 01:51:20
栏目: 编程语言

当然可以!首先,我们需要定义一个简单的 Point 类,包含 x 和 y 坐标以及相应的构造函数、拷贝构造函数、赋值运算符等。然后,我们可以为这个类添加一些操作坐标的方法。以下是一个简单的示例:

#include <iostream>

class Point {
public:
    // 默认构造函数
    Point() : x(0), y(0) {}

    // 带参数的构造函数
    Point(double x, double y) : x(x), y(y) {}

    // 拷贝构造函数
    Point(const Point& other) : x(other.x), y(other.y) {}

    // 赋值运算符
    Point& operator=(const Point& other) {
        if (this != &other) {
            x = other.x;
            y = other.y;
        }
        return *this;
    }

    // 获取 x 坐标
    double getX() const {
        return x;
    }

    // 获取 y 坐标
    double getY() const {
        return y;
    }

    // 设置 x 坐标
    void setX(double x) {
        this->x = x;
    }

    // 设置 y 坐标
    void setY(double y) {
        this->y = y;
    }

    // 打印点坐标
    void print() const {
        std::cout << "Point("<< x << ", "<< y << ")" << std::endl;
    }

private:
    double x, y;
};

int main() {
    Point p1(3.0, 4.0);
    p1.print(); // 输出:Point(3, 4)

    Point p2(p1); // 使用拷贝构造函数
    p2.print(); // 输出:Point(3, 4)

    p1.setX(5.0);
    p1.setY(6.0);
    p1.print(); // 输出:Point(5, 6)

    Point p3;
    p3 = p1; // 使用赋值运算符
    p3.print(); // 输出:Point(5, 6)

    return 0;
}

这个简单的例子展示了如何用 C++ 的 Point 类实现坐标操作。你可以根据需要扩展此类,添加更多的功能。

0