友元
-
定义:类的特点是私有成员无法在作用域外访问,而友元函数是特权函数,允许访问私有成员。
-
语法:在函数或类前加friend。
-
例子:在message中,published每个人都可访问,secret只有自己可以访问。但有时也需要秘密接头人访问secret。
-
注意事项:
1.友元关系不能被继承。
2.友元关系是单向的,类A是类B的朋友,但类B不一定是类A的朋友。
3.友元关系不具有传递性。类B是类A的朋友,类C是类B的朋友,但类C不一定是类A的朋友
14.1 普通成员函数作为类的友元
#include<iostream>
using namespace std;
class message {
private:
string secret;
public:
string published;
public:
message(string _secret, string _published) {
secret = _secret;
published = _published;
}
private:
friend void visiting(message &m) {
cout <<"secret: "<< m.secret << endl;
cout << "published: " << m.published << endl;
}
};
int main()
{
message paper("aaa","bbb");
visiting(paper);
}

14.2 类的成员函数作为另一类的友元
#include<iostream>
using namespace std;
class massege; //需要引用的类要在前面声明
class spy {
public:
void visiting_1(massege& paper);//不做为友元
void visiting_2(massege& paper);//做为友元
};
class massege {
public:
string publishing;
private:
string secret;
public:
massege(string _publishing, string _secret) {
publishing = _publishing;
secret = _secret;
}
private:
friend void spy::visiting_2(massege &paper);
};
void spy::visiting_1(massege& paper) {
cout << "visiting_1 publishing:" << paper.publishing << endl;
cout << "visiting_1 can't visit secret!" << endl;
}
void spy::visiting_2(massege& paper) {
cout << "visiting_2 publishing:" << paper.publishing << endl;
cout << "visiting_2 secret:" << paper.secret << endl;
}
int main()
{
massege paper("ppppp","sssss");
spy YY;
YY.visiting_1(paper);
YY.visiting_2(paper);
}

14.3 整个类作为另一个类的友元
#include<iostream>
using namespace std;
class massege; //需要引用的类要在前面声明
class spy {
public:
void visiting_1(massege& paper);//不做为友元
void visiting_2(massege& paper);//做为友元
};
class massege {
public:
string publishing;
private:
string secret;
public:
massege(string _publishing, string _secret) {
publishing = _publishing;
secret = _secret;
}
private:
friend spy;
};
void spy::visiting_1(massege& paper) {
cout << "visiting_1 publishing:" << paper.publishing << endl;
cout << "visiting_2 secret:" << paper.secret << endl;
}
void spy::visiting_2(massege& paper) {
cout << "visiting_2 publishing:" << paper.publishing << endl;
cout << "visiting_2 secret:" << paper.secret << endl;
}
int main()
{
massege paper("ppppp","sssss");
spy YY;
YY.visiting_1(paper);
YY.visiting_2(paper);
}


![[附源码]java毕业设计校园博客系统](https://img-blog.csdnimg.cn/7cc144ee874340afbd9b42bd24ada652.png)
















