Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/129.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何使用friend class c++;_C++ - Fatal编程技术网

C++ 如何使用friend class c++;

C++ 如何使用friend class c++;,c++,C++,我有一个矩形类和一个朋友点类。我使用笛卡尔坐标,所以矩形类中有四个点。点在点类中定义。在源文件中定义矩形构造函数时,我得到错误(在注释中标记): 矩形没有成员矩形 标题: using namespace std; class Rectangle { public: Rectangle(Point, Point, Point, Point); friend class Point; ~Rectangle(); private: Point a; Point

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

矩形没有成员矩形

标题:

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("");
    }
}
来源:

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::Rectangle(点v1、点v2、点v3、点v4)//此处出错
{
}
点::点(int值1,int值2)
{

如果(x删除构造函数声明中的星号

向前声明点,或在矩形前声明点


您也确实不应该在头文件中使用“using namespace”。

您的
矩形
构造函数中会出现编译器错误,因为
在头文件中未声明的情况下使用,您需要先定义
类,或者直接向前声明它:

class Point;

friend class
friend
通常用于使stuff访问类私有成员,例如,如果您希望使用全局函数访问类私有成员,您可以执行以下操作:

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;
}
klass类{
私人:
INTV;

friend ostream&Operator第一:你需要
成为
矩形
朋友
的理由是什么?我想不出任何好的理由。第二:要修正你的错误,在声明
类矩形
之前,向前声明
类点;
。你应该提到你遇到的错误。避免
朋友
>-更麻烦的是它的价值。@juanchopanza他/她确实提到了它。从这一点翻译过来,编译器说…@πάνταῥεῖ 啊,是的,很好。fwd声明是构造函数声明所必需的。oops应该是粗体的