[英]Accessing variables in nested classes
我已經嵌套了一個在另一個類中使用的類,需要嘗試訪問它的各個部分但不能。 我該怎么做呢?
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值?
如果你真的想這樣做,那么你可以讓這些課成為朋友。
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的情況下使用(例如 - 也許它也用於三角形)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.