友元函数
定义
- C++中引入友元函数,是为在该类中提供一个对外(除了他自己意外)访问的窗口;
- 这个友元函数他不属于该类的成员函数,他是定义在类外的普通函数,只是在类中声明该函数可以直接访问类中的private或者protected成员。
使用友元函数声明的一般形式:
1
| friend <返回类型> <函数名> (<参数列表>);
|
使用友元函数注意的要点:
- 类中通过使用关键字friend 来修饰友元函数,但该函数并不是类的成员函数,其声明可以放在类的私有部分,也可放在共有部分。友元函数的定义在类体外实现,不需要加类限定。
- 一个类中的成员函数可以是另外一个类的友元函数,而且一个函数可以是多个类友元函数。
- 友元函数可以访问类中的私有成员和其他数据,但是访问不可直接使用数据成员,需要通过对对象进行引用。
- 友元函数在调用上同一般函数一样,不必通过对对象进行引用。
使用示例
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); 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; }
void setweigth(persion &pn,int w) { strcpy(pn.name,pn); pn.weigth=w; } void main() { persion p("zhansan"); 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); private: char name[20]; }; car::car(char *pn) { strcpy(name,pn); } class wheel{ public: wheel(int s); friend void car::run(wheel &w); 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) { cout<<"the car is running"<<endl; cout<<"name: "<<name<<" speed :"<<w.speed<<endl; }
|
友元函数没有this指针(因为友元函数不是类的成员),所以参数有三种情况:
1、访问非static成员时需要对象做参数。
2、访问static成员或全局变量时不需要对象做参数
3、如果做参数的对象是全局对象,则不需要对象做参数
使用:
友元函数
流运算符<<、>>、类型转换运算符不能定义为类的成员函数,只能是友元函数。
二元运算符在运算符重载时,一般声明为友元函数