【问题标题】:Accessing variables in nested classes访问嵌套类中的变量
【发布时间】:2015-04-17 17:34:42
【问题描述】:

我已经嵌套了一个类以在另一个类中使用,并且需要尝试访问它的各个部分但不能。我该怎么做呢?

class Point
{
public:
    Point() { float x = 0, y = 0; }   
    void Input(int &count);                      //input values
    Rectangle myRec;

private:
    float x, y;

};


class Rectangle
{
public:
    Rectangle();      //side1 - horizontal, side2 - vertical
    void SetPoint(const Point point1, const Point point2, const Point point3, const Point point4) { LLPoint = point1; LRPoint = point2; URPoint = point3; ULPoint = point4; }
    float CalcSides(Point LL, Point LR, Point UL, Point UR);

private:
    Point LLPoint, LRPoint, ULPoint, URPoint;       
    float side1, side2, length, width, area, perimeter;  //side1 - horizontal, side2 - vertical
};

float Rectangle::CalcSides(Point LL, Point LR, Point UL, Point UR)
{
    side1 = (LR.x - LL.x);
}

如何访问我在 Rectangle 类中创建的点的 x 和 y 值?

【问题讨论】:

  • 我忘了提到我在使用 Rectangle::CalcSides 函数时遇到了问题。它一直告诉我 x 值无法访问。

标签: c++ oop functional-programming inner-classes membership


【解决方案1】:

如果你真的想这样做,那么你可以让班级成为朋友。

class Rectangle;

class Point
{
    friend class Rectangle;

public:
    Point() { x = 0; y = 0; }   
    void Input(int &count);                      //input values

private:
    float x, y;    
};

但更有可能的是,您只是想向 Point 类添加访问器,因为它本来就没什么用处。

class Point
{
public:
    Point() { x = 0; y = 0; }   
    void Input(int &count);                      //input values

    float getX() const { return x; }
    float getY() const { return y; }

private:
    float x, y;    
};

或者,如果 Point 真的要这么简单并且根本不需要维护任何不变量,只需将 x 和 y 公开为公共成员。

此外,您可能不希望 Point 包含一个 Rectangle 而是通过指针或引用来引用一个,如果它完全引用了一个。毕竟,Point 在不参考 Rectangle 的情况下也很有用(例如 - 也许它也用于 Triangles)。

【讨论】:

    猜你喜欢
    • 2015-08-13
    • 2022-06-23
    • 1970-01-01
    • 2015-08-10
    • 1970-01-01
    • 2019-08-10
    • 2022-01-25
    • 2021-03-05
    • 1970-01-01
    相关资源
    最近更新 更多