友元的目的是让类外函数或者其他类访问到类内的私有属性。友元实现的三种方式:全局函数做友元、类做友元、成员函数做友元。
1、全局函数做友元
#include <iostream>
#include <string.h>
using namespace std;
class Home{
// 全局函数作为友元
friend void goodfriend(Home &home);
public:
Home(){
bedroom = "bed room";
livingroom = "living room";
}
string livingroom;
private:
string bedroom;
};
void goodfriend(Home &home){
cout << home.livingroom << endl;
cout << home.bedroom << endl;
}
void test(){
Home a;
goodfriend(a);
}
int main() {
test();
return 0;
}
2、类做友元
#include <iostream>
#include <string.h>
using namespace std;
class Home{
// 类作为友元
friend class Person;
public:
Home(){
bedroom = "bed room";
livingroom = "living room";
}
string livingroom;
private:
string bedroom;
};
class Person{
public:
Person(){
home = new Home;
}
void visit(){
cout << home->livingroom << endl;
// 作为友元即可访问该类的私有属性
cout << home->bedroom << endl;
}
private:
Home *home;
};
void test(){
Person p;
p.visit();
}
int main() {
test();
return 0;
}
3、成员函数做友元
#include <iostream>
#include <string.h>
using namespace std;
class Home;
class Person{
public:
// 不能在此处实现函数,因为Home类只进行声明并没有实现
Person();
void visit1();
void visit2();
private:
Home *home;
};
class Home{
// 成员函数作为友元
friend void Person::visit1();
public:
Home(){
bedroom = "bed room";
livingroom = "living room";
}
string livingroom;
private:
string bedroom;
};
// Person类中函数的实现,放在Home类实现之后
Person::Person(){
home = new Home;
}
void Person::visit1(){
cout << "visit1 " << home->livingroom << endl;
cout << "visit1 " << home->bedroom << endl;
}
void Person::visit2(){
cout << "visit2 " << home->livingroom << endl;
// 访问私有属性bedroom,不能进行,因为visit2不是Home类的友元
// cout << "visit2 " << home->bedroom << endl;
}
void test(){
Person p;
p.visit1();
p.visit2();
}
int main() {
test();
return 0;
}
|