如何使用友元类 c++

How to use friend class c++

本文关键字:c++ 友元 何使用      更新时间:2023-10-16

我有一个带有朋友点类的矩形类。我使用的是笛卡尔坐标,所以我在矩形类中有四个点。点在点类中定义。在源文件中定义矩形构造函数时,我收到错误(在注释中标记):

矩形没有成员 矩形

页眉:

using namespace std;
class Rectangle
{
public:
    Rectangle(Point, Point, Point, Point);
    friend class Point;
    ~Rectangle();
private:
    Point a;
    Point b;
    Point c;
    Point d;
};
class Point
{
public:
    Point(int, int);
private:
    int x;
    int y;
};

源:

Rectangle::Rectangle(Point v1, Point v2, Point v3, Point v4)    //error here
{
}
Point::Point(int value1, int value2)
{
    if (x <= 20 && y <= 20){
        x = value1;
        y = value2;
    }
    else{
        throw invalid_argument("");
    }
}

删除构造函数声明中的星号。

向前声明点

,或在矩形之前声明点。

您也确实不应该在头文件中使用"使用命名空间"。

您在

Rectangle 构造函数中收到编译器错误,因为Point在头文件中未声明,您需要在之前定义 Point 类,或者只是向前声明它:

class Point;

一般来说,friend classfriend旨在使东西访问类私有成员,例如,如果您希望全局函数访问类私有成员,则可以执行以下操作:

class klass {
private:
   int v;
   friend ostream& operator<<(ostream& os, const klass& k);
};
ostream& operator<<(ostream& os, const klass& k)
{
   os << k.v;
   return os;
}

因此,从您想要做的事情来看,您需要Point类中的friend class而不是Rectangle