如何使用友元类 c++
How to use friend class c++
我有一个带有朋友点类的矩形类。我使用的是笛卡尔坐标,所以我在矩形类中有四个点。点在点类中定义。在源文件中定义矩形构造函数时,我收到错误(在注释中标记):
矩形没有成员 矩形
页眉:
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 class
或friend
旨在使东西访问类私有成员,例如,如果您希望全局函数访问类私有成员,则可以执行以下操作:
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
相关文章:
- C++模板来检查友元函数的存在
- 模板类无法识别友元运算符
- 如何使用单独文件中的派生类访问友元函数对象
- 模板化的类和友元函数
- 为什么创建友元类的实例会导致"undefined reference to"错误?
- 如何在嵌套类中正确使用友元声明?
- 友元函数无法访问私有数据成员 (c++)
- 继承和友元函数,从基类访问受保护的成员
- 将子类方法声明为基类的友元
- 如何在友元函数中使用静态成员而不添加前缀 [类名]::
- 在将函数声明为友元时,尖括号的含义是什么?
- 在模板类之外定义友元函数的正确方法是什么?
- 2个模板化类的非模板友元函数未定义引用错误
- 友元方法作为常量
- C++ 友元函数和私有构造函数
- 使第二个类的构造函数成为第一个类中的友元函数
- 在为嵌套类定义行外友元时,我真的必须打破封装吗?
- 未定义的类模板不会实例化以检查友元函数
- C++类中的友元函数有问题?
- 使用typedef'ed返回类型声明友元函数时出现编译器错误