注意:如果一个类中的函数static修饰的函数,不能作为友元函数;
全局函数作友元:
1)全局函数的声明在类中
2)全局函数的定义在类外
3)加关键字friend
4)能够访问类的对象上的私有成员
#includeusing namespace std; class friend_global_function { friend void golbal_function(friend_global_function & obj);//在类中添加关键字firend修饰,并且声明 public: void pu_function() { cout<<"this is public function"< cout<<"this is private function"< obj.pu_function(); cout<<"pu="< friend_global_function obj; golbal_function(obj); }
类作友元:
1)假如A是B的友元类,那么A类的对象可以访问B类中的所有成员。
2)假如A是B的友元类,需要在A类中声明B类是A类的友元
3)假如A是B的友元类,A类的对象上的成员能够访问到B类对象上的成员
4)修饰关键字friend
例子1:
#includeusing namespace std; class m_h_friend { friend class as_friend; public: void m_h_friend_pu_function() { cout<<"this is m_h_frien_pu_function"< cout<<"this is m_h_friend_pr_function"< public: void as_friend_pu_function(m_h_friend &obj) { obj.m_h_friend_pu_function(); cout<<"pu_variable="< m_h_friend m_h_obj; as_friend as_obj; as_obj.as_friend_pu_function(m_h_obj); // m_h_obj.m_h_friend_pr_function();这样会报错,因为私有成员不能外部访问。 }
例子2:
#includeusing namespace std; class home { friend class god_gay; public: void drawing(); private: void bedroom(); }; class god_gay { public: god_gay() { this->my_home=new home;//在堆区开辟一个空间存放类的对象的指针并且将该指针返回赋值给my_home } void into_home(); private: home *my_home; }; void god_gay::into_home() { my_home->bedroom(); my_home->drawing(); } void home::drawing() { cout<<"drawing"< cout<<"bedromm"< god_gay gay; gay.into_home(); }
成员函数作友元
1)假设B类中的函数b_f()是A类的友元函数,那么在调用B类中的函数b_f()的时候调用该函数的对象可以访问A类对象上的私有成员。
2)假设B类中的函数b_f()是A类的友元函数,在声明b_f()是A类的友元函数之前,需要先在B类中声明b_f()函数,否则会报错。
例子;
#includeusing namespace std; class A; class B; class B { public: B(); void B_f1(); void B_f2();//注意函数的首次声明应该在声明它为友元成员函数之前。 A *a_obj; }; class A { friend void B::B_f2();//在声明这个函数为友元成员函数之前要先在它本来属于的类中先声明 public: A(); int A_variable; private: int A1_variable; }; //int A::A_variable=10;//不能在外部定义普通变量 A::A():A_variable(10),A1_variable(20) { } B::B() { a_obj=new A; } void B::B_f1() { cout< A_variable< cout< A_variable< A1_variable< B b; b.B_f1(); b.B_f2(); }



