1.友元函数
class A{
friend void MyFriend(class &A);
private:
int m_a;
}
void MyFriend(class &A)
{
std::cout << A.m_a << std::endl;
}
2.友元类
class A{
public:
A();
friend class B;
private:
int m_a;
}
class B{
public:
B();
void UseA(A &a);
}
void B::UseA(A &a)
{
std::cout<< a.m_a << std::endl;
}
3.友元成员函数
//注意声明顺序,保证可见
class A;//A做前置声明,因为B中要使用
class B{
public:
B b();
void UseA(A &a);
}
class A{
public:
A();
friend void B::UsaA(A &a);
private:
int m_a;
}
void B::UseA(A &a){
std::cout << a.m_a << std::endl;
}
4.共同友元函数 (一个函数是两个类的友元)
class B;
class A{
public:
A();
friend void UseAB(A &a,B&b);
private:
int m_a;
}
class B{
public:
B();
friend void UsaAB(A &a,B &b);
private:
int m_a;
}
void UseAB(A &a,B &b)
{
std::cout << a.m_a + b.m_a << std::endl;
}
友元是对类接口的扩展,因为只有在类中才能指定谁为友元,so,不违反OOP思想!