在C++程序中,有些私有属性也想让类外特殊的一些函数或者类进行访问,就可以使用友元技术。 友元的目的是让一个函数或者类访问另一个类中的私有成员 。友元的关键字为friend 。
全局函数做友元
#include<iostream>
using namespace std;
#include<string>
class Building {
friend void bestfriend(Building& building);
public:
Building() {
sittingroom = "客厅";
bedroom = "卧室";
}
public:
string sittingroom;
private:
string bedroom;
};
void bestfriend(Building &building) {
cout << "全局函数正在访问" << building.sittingroom << endl;
cout << "全局函数正在访问" << building.bedroom << endl;
}
void test01() {
Building b1;
bestfriend(b1);
}
int main() {
test01();
system("pause");
return 0;
}
类做友元
#include<iostream>
#include<string>
using namespace std;
class Building {
friend class Bestfriend;
public:
Building();
public:
string sittingroom;
private:
string bedroom;
};
class Bestfriend {
public:
Bestfriend();
void visit();
Building* building;
};
Building::Building() {
sittingroom = "客厅";
bedroom = "卧室";
}
Bestfriend::Bestfriend() {
building = new Building;
}
void Bestfriend::visit(){
cout << "Bestfriend类正在访问" << building->sittingroom << endl;
cout << "Bestfriend类正在访问" << building->bedroom << endl;
}
void test01() {
Bestfriend b1;
b1.visit();
}
int main() {
test01();
system("pause");
return 0;
}
成员函数做友元
#include<iostream>
#include<string>
using namespace std;
class Building;
class Bestfriend;
class Bestfriend {
public:
Bestfriend();
void visit1();
void visit2();
Building* building;
};
class Building {
friend void Bestfriend::visit1();
public:
Building();
public:
string m_sitroom;
private:
string m_bedroom;
};
Building::Building() {
m_sitroom = "客厅";
m_bedroom = "卧室";
}
Bestfriend::Bestfriend() {
building = new Building;
}
void Bestfriend::visit1() {
cout << "visit1正在访问" << building->m_sitroom << endl;
cout << "visit1正在访问" << building->m_bedroom << endl;
}
void Bestfriend::visit2() {
cout << "visit2正在访问" << building->m_sitroom << endl;
}
void test01() {
Bestfriend b1;
b1.visit1();
b1.visit2();
}
int main() {
test01();
system("pause");
return 0;
}
|