访问嵌套类中的变量

时间:2015-02-17 04:06:35

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

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

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值?

1 个答案:

答案 0 :(得分:0)

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

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的情况下使用(例如 - 也许它也用于三角形)。