类可以允许其他类或函数访问它的非公有成员,方法是令其他类或函数成为它的友元(friend)。
应用对象: 函数 ——- 友员函数
类 ——- 友员类
功 能:提供了在类的外部访问类中的
所有成员的途径
弊 端:一定程度上破坏了类的封装性
备 注:友员关系不受类中访问修饰符的限制
1.友元函数
class Test
{
int m_data;
public:
Test(int data):m_data(data){}
~Test(){}
//声明 show() 是Test的友元函数
friend void show(Test &t);
};
void show(Test &t)
{
cout << “t.m_data = ” << t.m_data << endl;
return;
}
int main(int argc,char *argv[])
{
Test t(123);
show(t);
return 0;
}
2.友元类
class Test
{
int m_data;
public:
Test(int data):m_data(data){}
~Test(){}
//声明Brother是Test的友元类
friend class Brother;
};
class Brother
{
public:
Brother(){}
~Brother(){}
void show(Test &t)
{
cout << "t.m_data = " << t.m_data << endl;
return;
}
};
int main(int argc,char *argv[])
{
Test t(123);
Brother b;
b.show(t);
return 0;
}
3.友元类间的关系
友员类性质:1.不能继承 - 父亲的朋友不是你的朋友
2.不能传递 - 朋友的朋友不是你的朋友
3.不能反转 - 你的就是我的,但是我的还是我的
class Test
{
int m_data;
public:
Test(int data):m_data(data){}
~Test(){}
friend class Father;
friend class Brother;
void show(Test &t)
{
cout << “Test data=” << t.m_data << endl;
return;
}
};
class Brother
{
public:
Brother(){}
~Brother(){}
friend class Son;
};
class Father
{
public:
Father(){}
~Father(){}
void show(Test &t)
{
cout << "Father data=" << t.m_data << endl;
return;
}
};
class Son:public Father
{
public:
Son(){}
~Son(){}
void show(Test &t)
{
cout << "Son data=" << t.m_data << endl;
return;
}
};
int main(int argc,char *argv[])
{
Test t(123);
Father f;
f.show(t);
// Son s;
// s.show(t); //error
return 0;
}