简体   繁体   中英

Accessing variables in nested classes

I've nested a class for use within another class and need to try accessing individual parts of it but can't. How would I go about doing this?

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);
}

How can I access the x and y values for the points I've created in the Rectangle class?

If you really want to do this, then you can make the classes friends.

class Rectangle;

class Point
{
    friend class Rectangle;

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

private:
    float x, y;    
};

More likely though, you simply want to add accessors to the Point class as it is fairly useless as is.

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;    
};

Or, if Point is really going to be so simple and not need to maintain any invariants at all, just expose x and y as public members.

Also, you probably don't want to have Point contain a Rectangle but rather refer to one either through a pointer or a reference, if it refers to one at all. After all, a Point can be useful without reference to a Rectangle (eg - maybe it's used for Triangles too).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM