1.未设置友元时:
//不设置友元的情况,类外的全局函数无法访问私有成员
#include <iostream>
#include<string>
using namespace std;
class building {
public:
string m_bed;
building(string name1, string name2) {
m_bed = name1;
m_pub = name2;
}
private:
string m_pub;
};
void fun() {
building build("longge","niubi");
cout << "访问:" << build.m_bed << endl;
cout << "访问:" << build.m_pub << endl;
}
int main() {
fun();
}

2.设置了友元后:
//设置了友元后
#include <iostream>
#include<string>
using namespace std;
class building {
friend void fun();//友元函数的设置语法,写在哪里都可以?
public:
string m_bed;
building(string name1, string name2) {
m_bed = name1;
m_pub = name2;
}
private:
string m_pub;
};
void fun() {
building build("longge","niubi");
cout << "访问:" << build.m_bed << endl;
cout << "访问:" << build.m_pub << endl;
}
int main() {
fun();
}

3.示例三:
和示例二一样都是i正常的写法,不过这个换成了指针形式的函数之间传递参数。博采众长,多了解了解
#include <iostream>
#include<string>
using namespace std;
class building {
public:
friend void fun(building *build);
string m_bed;
building(string name1, string name2) {
m_bed = name1;
m_pub = name2;
}
private:
string m_pub;
};
void fun(building *build){
cout << "访问:" << build->m_bed << endl;
cout << "访问:" << build->m_pub << endl;
}
int main() {
building build("longge", "niubi");
fun(&build);
}
博客围绕C++展开,介绍了未设置友元、设置友元的情况,还给出示例三,该示例采用指针形式在函数间传递参数,与示例二写法类似,旨在让读者博采众长。
495





