2014-02-19 28 views
-2

我有一個朋友Point類的Rectangle類。我使用笛卡爾座標,所以我在矩形類中有四個點。點在點類中定義。如果數據初始化如下:如何訪問朋友類中的變量

int main() 
{ 
    Point w(1.0, 1.0); 
    Point x(5.0, 1.0); 
    Point y(5.0, 3.0); 
    Point z(1.0, 3.0); 

    Rectangle r1(x, y, z, w); 
} 

如何從r1打印所有點?此外,我需要使用4個點作爲矩形,並使用朋友類。

頭:

class Point 
{ 
public: 
    Point(); 
    Point(int, int); 
    void printPoint(Rectangle& pt, Point a); 
private: 
    int x; 
    int y; 
}; 

class Rectangle 
{ 
public: 
    Rectangle(Point, Point, Point, Point); 
    friend void Point::printPoint(Rectangle& pt, Point a); 
    ~Rectangle(); 
private: 
    Point a; 
    Point b; 
    Point c; 
    Point d; 
}; 
+0

你能具體談談什麼是錯的? –

+0

兩個點定義了一個(直線)矩形,而不是四個... – Potatoswatter

+0

只是爲了使事情變得有趣:a)您不需要四個點來定義矩形,只需要兩個(左上角和右下角)b)Point :: PrintPoint(並不需要任何參數 - 它被稱爲獲得一個點打印本身,c)不需要朋友的東西 –

回答

3

最起碼,你需要轉發Point類定義之前聲明Rectangle。這是因爲void printPoint(Rectangle& pt, Point a);成員函數需要聲明。

class Rectangle; // fwd declaration 

class Point 
{ 
public: 
    // as before 

除此之外,很難說,因爲你沒有提示你遇到什麼問題。你甚至不清楚你爲什麼需要友誼以及你打算如何使用它。

+0

這是班級的作業。我們覆蓋了朋友功能,但不包括朋友類。我想要做的就是打印r1中的點。 – reezolv

0

要打印一個矩形的頂點RectanglePoint都需要打印方法。
請注意,矩形打印點;點不打印矩形。

class Point 
{ 
    public: 
    void print(std::ostream& out) 
    { 
     out << "(' << x << ", " << y << ")"; 
    } 
}; 

class Rectangle 
{ 
    public: 
    void print(std::ostream& out) 
    { 
     a.print(out); out << "\n"; 
     b.print(out); out << "\n"; 
     c.print(out); out << "\n"; 
     d.print(out); out << "\n"; 
    } 
}; 

我建議你重載operator << (std::ostream&)使矩形的印刷和頂點更容易。 研究爲「C++重載操作員ostream」提供了一些例子。

0

不清楚你想要做什麼.. 我假設你想用矩形對象打印點。

但我發現你不能聲明函數是類的友元函數首先定義之前類內部的朋友..

class Rectangle; 
class Point 
{ 
.. 
private: 
    int x, y; 
friend void Rectangle::PrintRectangle(); // doesn't work 

我認爲你需要重新設計你的類..

class Rectangle; 

class Point 
{ 
public: 
    Point(); 
    Point(int, int); 
    void printPoint(); // take out the rectangle parameter here.. and also the point.. use reference to the object (this->) 
private: 
    int x; 
    int y; 
    friend Class Rectangle; // declare friend class 
}; 

然後在Rectangle類中定義PrintRectangle();

class Rectangle 
{ 
public: 
    Rectangle(Point, Point, Point, Point); 
    void PrintRectangle(); // 
    ~Rectangle(); 
private: 
    Point a; 
    Point b; 
    Point c; 
    Point d; 
}; 

在printrectangle您可以訪問Point對象的私人數據..

void Rectangle::PrintRectangle() 
{ 
    int x; 
    x = this->a.x; 
}