友元,就是相当远是朋友,是铁哥们,是兄弟,兄弟间就可以相互知道各自的秘密,这里的秘密就相当于类中私有成员,朋友兄弟,就是被声明成友元的类或者函数。(注意:友元不能被继承,就像兄弟是两个人的事,与其他后来者无关)
类的友元:
声明成类的友元,则该内即可访问友元类的私有成员; (注:声明了友元类的类才能访问被友元声明的类的私有成员)
struct Secret
{
CString girlFriendName;
CString ownStroy;
int characterType;
};
class LittleBrother
{
LittleBrother();
private:
Secret sercet;
}
class BigBrother
{
public:
BigBrother();
friend class LittleBrother;
void GetMyBroSecret(LittleBrother myLittleBrother);//此函数即可访问myLittleBrother对象的私有成员
}
友元函数:
被类声明的友元函数,即可访问类中的私有成员;
class Person
{
public:
friend void StealSecret(Person person);//友元函数
privete:
Secret secret;
}
void StealSecret(Person person)
{
cout<<person.secret.girfrientName<<endl;
}
友元成员函数:
同理友元函数,不同的是函数被声明在类中;
再次注明:友元用于访问类的私有成员,友元不能被继承;