c++

能否用C++的point类实现自定义的坐标系

小樊
82
2024-09-25 02:01:15
栏目: 编程语言

当然可以。首先,我们需要定义一个表示点的类(Point),然后实现一些基本的几何操作,如向量加法、减法、标量乘法、点积和叉积等。以下是一个简单的示例:

#include <iostream>

class Point {
public:
    double x, y;

    // 构造函数
    Point(double x = 0, double y = 0) : x(x), y(y) {}

    // 向量加法
    Point operator+(const Point& other) const {
        return Point(x + other.x, y + other.y);
    }

    // 向量减法
    Point operator-(const Point& other) const {
        return Point(x - other.x, y - other.y);
    }

    // 标量乘法
    Point operator*(double scalar) const {
        return Point(x * scalar, y * scalar);
    }

    // 点积
    double dot(const Point& other) const {
        return x * other.x + y * other.y;
    }

    // 叉积(仅适用于二维)
    double cross(const Point& other) const {
        return x * other.y - y * other.x;
    }

    // 输出点的坐标
    friend std::ostream& operator<<(std::ostream& os, const Point& point) {
        os << "(" << point.x << ", " << point.y << ")";
        return os;
    }
};

int main() {
    Point p1(3, 4);
    Point p2(1, 2);

    Point p3 = p1 + p2;
    Point p4 = p1 - p2;
    Point p5 = p1 * 2;

    std::cout << "p1 + p2 = " << p3 << std::endl;
    std::cout << "p1 - p2 = " << p4 << std::endl;
    std::cout << "2 * p1 = " << p5 << std::endl;
    std::cout << "p1 · p2 = " << p1.dot(p2) << std::endl;
    std::cout << "p1 × p2 = " << p1.cross(p2) << std::endl;

    return 0;
}

这个简单的示例展示了如何使用C++实现一个自定义的坐标系。你可以根据需要扩展这个类,添加更多的几何操作和成员函数。

0
看了该问题的人还看了