不用复杂长到不想看的文章,几句话,测试代码运行一遍,马上了解友元
类的友元函数是定义在类外部,但有权访问类的所有私有(private)成员和保护(protected)成员。尽管友元函数的原型有在类的定义中出现过,但是友元函数并不是成员函数。
因为友元函数不是成员函数所以没有this指针,则参数要有几种情况:
要访问非static成员时,需要对象做参数;
要访问static成员或全局变量时,则不需要对象做参数;
#include <iostream>
#include <bits/stdc++.h> //c++万能头
using namespace std;
class Box
{
int width;
static int height;
public:
void setwidth(int wid);
//将printwidth设置为Box的友元函数,printwidth就可以访问Box类的保护成员和私有成员
friend void printwidth(Box& box);
friend void printheight();
//将Bigbox设置为Box的友元类,Bigbox就可以访问Box类的保护成员和私有成员
friend class Bigbox;
};
class Bigbox
{
public:
void Print(Box& box,int wid);
};
int Box::height=10;
void Box::setwidth(int wid)
{
this->width=wid;
}
void Bigbox::Print(Box &box, int wid)
{
box.setwidth(wid);
cout<<box.width<<endl;
}
void printwidth(Box& box)
{
cout<<box.width<<endl;
}
void printheight()
{
cout<<Box::height<<endl;
}
int main()
{
Box boxt;
boxt.setwidth(5);
printwidth(boxt);
printheight();//调用静态变量无需借助对象
Bigbox bbox;
bbox.Print(boxt,20);
printwidth(boxt);
}
运行结果