如何访问朋友类中的变量

时间:2014-02-19 23:37:04

标签: c++

我有一个带有朋友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;
};

3 个答案:

答案 0 :(得分:3)

至少,您需要在Rectangle类定义之前转发声明Point。这是因为void printPoint(Rectangle& pt, Point a);成员函数需要声明。

class Rectangle; // fwd declaration

class Point
{
public:
  // as before

除此之外,很难说,因为你没有提示你遇到的问题。甚至不清楚为什么你需要友谊以及你打算如何使用它。

答案 1 :(得分:0)

要打印矩形的顶点RectanglePoint都需要打印方法。
注意Rectangle打印Points;点不打印矩形。

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”的网页,为您提供一些示例。

答案 2 :(得分: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;
}