理解C++中的friend class
文章标签
MySQL Workbench
一、friend class的概念
C++中的friend关键字用于在类定义中声明其他类或函数为友元,这样它们就可以访问类的私有成员。而friend class则用于声明一整个类为友元。
当一个类被声明为另一个类的友元时,它可以访问该类的私有成员,但并不具备该类的成员函数或方法。而当一个类被声明为另一个类的friend class时,它可以访问该类的私有成员和成员函数或方法。
二、friend class的使用场景
friend class的使用场景多种多样,下面介绍其中两种典型的情境。
1.友元类与封装的关系:
class Box
{
private:
int length;
int width;
int height;
public:
Box(int l = 0, int w = 0, int h = 0)
{
length = l;
width = w;
height = h;
}
friend class BoxVolume; // 声明BoxVolume类为Box的友元类
};
class BoxVolume
{
public:
int getVolume(Box &box) {
return box.length * box.width * box.height;
}
};
在上面的示例中,我们声明BoxVolume类为Box类的友元类,这样BoxVolume类就可以访问Box类的私有成员length、width和height,并利用它们计算出Box的体积。
2.友元类与继承的关系:
class Fruit
{
protected: // 注意这里使用protected而不是private
int weight;
public:
Fruit(int w) : weight(w) {}
void showWeight() {
std::cout 版权声明
本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。
上一篇:掌握C++强制类型转换技巧,提高程序准确性! 下一篇:判断C++中的闰年
code前端网
