【问题标题】:c++ non-member function using a class which references another classc++ 使用引用另一个类的类的非成员函数
【发布时间】:2019-03-04 02:40:18
【问题描述】:

我有这个硬件问题,我已经被困了几个小时,我似乎无法理解。很难用语言表达我的实际问题,但我会尽力而为。如何让我的外部成员函数使用引用另一个类的类找到圆之间的距离?在我下面的代码中:

//Header
class Point
{
public:
    Point();
    Point(int, int);
    Point(const Point& object);
    int getX() const;
    int getY() const;
    void setX(int);
    void setY(int);
    double calculate_area();
    void print() const;

private:
    int x;
    int y;
};

class Shape
{
public:
    Shape();
    double calculate_area();
    void print() const;

protected:
    double area;
};

class Circle : public Shape
{
public:
    Circle();
    Circle(const Point&, double);
    double getRadius() const;
    void setRadius(double);
    void calculate_area();
    void print() const;

private:
    double radius;
    Point center;
};

class RTriangle : public Shape
{
public:
    RTriangle();
    RTriangle(double, double);
    double hyp();
    void calculate_area();
    void print() const;

private:
    double side1;
    double side2;
};

inline double distance(Circle& other)
{
    return sqrt(pow(other.center.x, 2) + pow(other.center.y, 2));
}

#endif

//Implementation.cpp of what i think is important for you guys to see
Point::Point(int inX, int inY) // normal constructor
{
    x = inX;
    y = inY;
}

Point::Point(const Point &object) // copy constructor needed to use for center of circle
{
    x = object.x;
    y = object.y;
}
Circle::Circle(const Point& object, double inRad) // center is x & y... radius for circle
{
    center = object;
    radius = inRad;
}

我的外部成员函数(内联双距离)不起作用。这是我第一次尝试这样做,所以如果我说得不好,我深表歉意。我本质上是在尝试仅使用继承点中心的 Circle 类,并且点中心在第一个类中定义为 x 和 y。是否有可能做这样的事情(特别是使用点中心内的 x 和 y )?不知道能不能通过center访问x和y。

【问题讨论】:

  • 我也想这样做,但我的教授说不要这样做:(
  • 使您的距离函数类成员并修复您使用的距离公式。
  • 圆不继承中心;它继承自 Shape,但 center 是它自己的成员。这个问题与继承无关,只是访问控制。

标签: c++ inheritance composition


【解决方案1】:

给定一个 Point,不在 Point 中的函数可以使用示例中的公共 getX() 和 getY() 方法访问其 x 和 y 成员。

但是,Circle 的中心成员不是公共的,也没有公共访问者。最直接的解决方法是添加一个公共方法

点getCenter(); // 或者 Point const &getCenter() 如果你喜欢)

转圈。

【讨论】:

  • 我的教授希望我使用非成员函数,而不是使用公共函数。从您所见,我目前的设置是否可行?
  • 他们是否希望您不要将 distance() 声明为 Circle 的成员函数,或者在其实现中完全不使用 Circle 的任何公共方法?在后一种情况下,您可以将 free 函数声明为 Circle 的友元函数,但这应该是最后的手段。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-07-13
  • 1970-01-01
  • 1970-01-01
  • 2016-01-28
  • 1970-01-01
  • 2011-06-23
  • 1970-01-01
相关资源
最近更新 更多