溫馨提示×

能否用C++的point類實現(xiàn)坐標操作

c++
小樊
81
2024-09-25 01:51:20
欄目: 編程語言

當然可以!首先,我們需要定義一個簡單的 Point 類,包含 x 和 y 坐標以及相應(yīng)的構(gòu)造函數(shù)、拷貝構(gòu)造函數(shù)、賦值運算符等。然后,我們可以為這個類添加一些操作坐標的方法。以下是一個簡單的示例:

#include <iostream>

class Point {
public:
    // 默認構(gòu)造函數(shù)
    Point() : x(0), y(0) {}

    // 帶參數(shù)的構(gòu)造函數(shù)
    Point(double x, double y) : x(x), y(y) {}

    // 拷貝構(gòu)造函數(shù)
    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;
    }

    // 設(shè)置 x 坐標
    void setX(double x) {
        this->x = x;
    }

    // 設(shè)置 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); // 使用拷貝構(gòu)造函數(shù)
    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 類實現(xiàn)坐標操作。你可以根據(jù)需要擴展此類,添加更多的功能。

0