c++ - C++中的点和线类?

标签 c++ pointers

我正在学习 C++(和一般编程),我正在尝试制作一个 Point 类和一个 Line 类。

一条线应该由 2 个点对象组成。

C++ 专家能否查看我的工作并告诉我这是否是您应该正确使用指针、引用和类的方式?

class Point
{
    private:
        int x, y;
    public:
        Point() : x(0), y(0) {}
        Point(int x, int y) : x(x), y(y) {}
}

class Line
{
    private:
        Point *p1;
        Point *p2;
    public:
        Line(Point &p1, Point &p2) : p1(p1), p2(p2) {}

        void setPoints(Point &p1, Point &p2)
        {
            this->p1 = p1;
            this->p2 = p2;
        }
}

最佳答案

您根本不应该在代码中使用指针。使用实际对象。在 C++ 中实际上很少使用指针。

class Point
{
    private:
        int x, y;
    public:
        Point() : x(0), y(0) {}
        Point(int x, int y) : x(x), y(y) {}
}

class Line
{
    private:
        Point p1;
        Point p2;
    public:
        Line(const Point & p1, const Point & p2 ) : p1(p1), p2(p2) {}

        void setPoints( const Point & ap1, const Point & ap2)
        {
            p1 = ap1;
            p2 = ap2;
        }
}

关于c++ - C++中的点和线类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/564877/

相关文章:

c++ - 为什么这个函数会出现段错误?

c++ - cl_context 和 cl::Context 的区别

c++ - 提升精神QI : Auto-rule deduction on a tuple with a sequence inside an alternative function

c++ - GDB 回溯告诉我符号名称而不是源文件

c++ - 在模板类中设置函数指针的问题

pointers - 什么是 "fat pointer"?

c++ - Int 值奇怪地类似于指针

c++ - 在一系列 char* 缓冲区中寻找序列号?

c++ child 适合他们的 parent 吗?

c++ - C++ 编译器如何扩展模板 <> 代码以及它如何影响相同的速度?