【问题标题】:Distance and midpoint - which belongs to Point and which belongs to Line?距离和中点——哪个属于Point,哪个属于Line?
【发布时间】:2018-01-06 19:19:17
【问题描述】:

从面向对象编程的角度来看,给定两个类:Line(两个点)和 Point(两个浮点数)。哪个应该持有函数distance(),哪个应该持有midpoint()

我最初的想法是midpoint()应该属于Line,distance()属于Point,因为Point应该知道它自己和另一个点之间的距离。而midpoint() 更多的是第三人称计算,它审查两个点。

但是,当我想到它时,我意识到一个点知道它的 X 和 Y 坐标。所以这两个函数都应该属于Point。这也将保存getX()getY() getter 的创建。 Line 可以为自己的 Points 调用这些函数。

或者 Line 应该同时具备这两个功能?

那么哪个是正确的?或者..还有其他选择吗?

【问题讨论】:

  • 我总是将distance 放入Point但是 而不是0,0 而不是另一个点。一些例子^len = (new SubstractedPoint(pointA, pointB)).distance()。显然,这不是性能方面的。

标签: java oop computer-science


【解决方案1】:

你必须在 Line 类中制作距离函数和中点函数! 因为这两个功能都需要两点。 下面我给出的代码示例是类点有两个名为“x”和“y”的浮动变量,getx 和 gety 函数。另一个类 Line 具有与点类聚合并具有两个对象 p1 和 p2 用于计算两点与中点之间的距离。

class point
{

    float x, y;

public:
    float getx()
    {
        return x;
    }

    float gety()
    {
        return y;
    }

    void setx(float _x)
    {
        x=_x;
    }

    void sety(float _y)
    {
        y=_y;
    }
};

class line
{

    point p1, p2;

public:

    void distance()
    {
        cout << "Distance : " << sqrt(pow((p2.getx() - p1.getx()), 2) + pow((p2.gety() - p1.getx()), 2));
    }

    void midpoint()
    {
        cout << "Mid point : (" << ((p1.getx() + p2.getx()) / 2) << " , " << ((p1.gety() + p2.gety()) / 2) << " )";
    }
};

void main()
{
    // calling object
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-25
    • 2015-07-21
    • 2017-04-09
    • 1970-01-01
    • 2018-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多