友元函数

定义

  1. C++中引入友元函数,是为在该类中提供一个对外(除了他自己意外)访问的窗口;
  2. 这个友元函数他不属于该类的成员函数,他是定义在类外的普通函数,只是在类中声明该函数可以直接访问类中的private或者protected成员。

使用友元函数声明的一般形式:

1
friend <返回类型> <函数名> (<参数列表>);

使用友元函数注意的要点:

  1. 类中通过使用关键字friend 来修饰友元函数,但该函数并不是类的成员函数,其声明可以放在类的私有部分,也可放在共有部分友元函数的定义在类体外实现,不需要加类限定。
  2. 一个类中的成员函数可以是另外一个类的友元函数,而且一个函数可以是多个类友元函数。
  3. 友元函数可以访问类中的私有成员和其他数据,但是访问不可直接使用数据成员,需要通过对对象进行引用。
  4. 友元函数在调用上同一般函数一样,不必通过对对象进行引用。

使用示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

#include <iostream>
#include <cstring>
using namespace std;
class persion{
public:
persion(char *pn);
//友元函数;
friend void setweigth(persion &p,int h);//注意,参数列表中一般会有一个引用类型的形参,原因参考上面的使用要点3和4;
void disp(); //类成员函数
private:
char name[20];
int weigth,age;
};
persion::persion(char *pn) //构造函数
{
strcpy(name,pn);
weigth=0;
}
void persion::disp()
{
cout<<name<<"--"<<weigth<<endl;
}
//友元函数的具体实现:这里没有类限定例如 (perion::setweigth)这种形式,这里可以与上面的disp()做个对比,一个属于类的成员,有限定,不属于类的成员函数,没有加限定。
void setweigth(persion &pn,int w)
{
strcpy(pn.name,pn);//实现字符串复制
pn.weigth=w; //私有成员数据赋值

}
void main()
{
persion p("zhansan");
//调用实现setweigth(),与一般函数调用一致。
setweigth(p,60);
p.disp(); //调用类的成员函数。

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
2点示例
#include <iostream>
#include <cstring>
using namespace std;

class wheel;
class car{
public:
car(char *pn);
void run(wheel &w); //成员函数,做成wheel类中友元函数实现
private:
char name[20];

};
car::car(char *pn)
{
strcpy(name,pn);
}

class wheel{
public:
wheel(int s);
friend void car::run(wheel &w); //这里把car类的成员函数做了友元函数。
private:
int speed;
};
wheel::wheel(int s)
{
speed=s;
}
int main(int argc, char const *argv[])
{
wheel w(60);
car c("New car");
c.run(w);
return 0;
}

void car::run(wheel &w) //car类成员函数的实现
{
cout<<"the car is running"<<endl;
cout<<"name: "<<name<<" speed :"<<w.speed<<endl;
}

友元函数没有this指针(因为友元函数不是类的成员),所以参数有三种情况:

1、访问非static成员时需要对象做参数。

2、访问static成员或全局变量时不需要对象做参数

3、如果做参数的对象是全局对象,则不需要对象做参数

使用:

友元函数
流运算符<<、>>、类型转换运算符不能定义为类的成员函数,只能是友元函数。
二元运算符在运算符重载时,一般声明为友元函数