在程序里,有些私有属性想让类外一些函数或者类进行访问,就需要用到友元的技术,友元的目的就是让一个函数或者类访问另一个类中私有成员。
关键字:friend
三种实现方式
1、全局函数做友元
语法:friend void 函数名();
class student {
friend void goodGay(student* s);
public:
string name;
student() {
name = "张三";
id = 111111;
}
private:
int id;
};
//全局函数
void goodGay(student *s) {
cout << "访问姓名"<<s->name << endl;
cout << "访问ID:" << s->id << endl;
}
void test() {
student s1;
goodGay(&s1);
}
2、类做友元
语法:friend class 类名;
class student {
//类友元
friend class goodGay;
public:
string name;
student();
private:
int id;
};
//类外写成员函数
student::student() {
name = "张三";
id = 111111;
}
//全局函数
class goodGay {
public:
goodGay();
void visit();//访问student中的属性
private:
student* s;
};
goodGay::goodGay() {
s = new student;
}
void goodGay::visit() {
cout << "goodGay正在访问" << s->name << endl;
cout << "goodGay正在访问" << s->id << endl;
}
void test() {
goodGay g;
g.visit();
}
3、成员函数做友元
语法:friend void 类名::函数名();
class GoodGay;
class student;
class GoodGay {
public:
GoodGay();
public:
void visit();//可访问私有成员
void visit1();//不可访问私有成员
private:
student* s;
};
class student {
friend void GoodGay::visit1();
public:
string name;
student();
private:
int id;
};
//类外写成员函数
student::student() {
name = "张三";
id = 111111;
}
GoodGay::GoodGay() {
s = new student;
}
void GoodGay::visit() {
cout << "goodGayDevisit正在访问" << s->name << endl;
}
void GoodGay::visit1() {
cout << "goodGayDevisit1正在访问" << s->name << endl;
cout << "goodGayDevisit1正在访问" << s->id << endl;
}