注意:如果一个类中的函数static修饰的函数,不能作为友元函数;
全局函数作友元: 1)全局函数的声明在类中 2)全局函数的定义在类外 3)加关键字friend 4)能够访问类的对象上的私有成员
#include<iostream>
using namespace std;
class friend_global_function
{
friend void golbal_function(friend_global_function & obj);
public:
void pu_function()
{
cout<<"this is public function"<<endl;
}
int pu_variable=10;
private:
void pr_function()
{
cout<<"this is private function"<<endl;
}
int pr_variable=20;
};
void golbal_function( friend_global_function & obj)
{
obj.pu_function();
cout<<"pu="<<obj.pu_variable<<endl;
obj.pr_function();
cout<<"pr="<<obj.pr_variable<<endl;
}
int main()
{
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:
#include<iostream>
using 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"<<endl;
}
int m_h_pu_variable=10;
private:
void m_h_friend_pr_function()
{
cout<<"this is m_h_friend_pr_function"<<endl;
}
int m_h_pr_variable=20;
};
class as_friend
{
public:
void as_friend_pu_function(m_h_friend &obj)
{
obj.m_h_friend_pu_function();
cout<<"pu_variable="<<obj.m_h_pu_variable<<endl;
obj.m_h_friend_pr_function();
cout<<"pr_variable="<<obj.m_h_pr_variable<<endl;
}
};
int main()
{
m_h_friend m_h_obj;
as_friend as_obj;
as_obj.as_friend_pu_function(m_h_obj);
}
例子2:
#include<iostream>
using 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;
}
void into_home();
private:
home *my_home;
};
void god_gay::into_home()
{
my_home->bedroom();
my_home->drawing();
}
void home::drawing()
{
cout<<"drawing"<<endl;
}
void home::bedroom()
{
cout<<"bedromm"<<endl;
}
int main()
{
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()函数,否则会报错。
例子;
#include<iostream>
using 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;
};
A::A():A_variable(10),A1_variable(20)
{
}
B::B()
{
a_obj=new A;
}
void B::B_f1()
{
cout<<a_obj->A_variable<<endl;
}
void B::B_f2()
{
cout<<a_obj->A_variable<<endl;
cout<<a_obj->A1_variable<<endl;
}
int main()
{
B b;
b.B_f1();
b.B_f2();
}
|