在程序中有时私有属性也想让类外特殊的一些函数或类进行访问,就需要用到友元的技术;
友元的目的就是让一个函数或类访问另一个类中私有成员;
友元关键字:friend
友元实现方法:
全局函数做友元;
类做友元;
成员函数做友元;
#include<iostream>
#include<string>
using namespace std;
class person {
//best函数时类的友元函数可以访问类中的私有成员
friend void best(person *p);
public:
string name = "caohai";
person() {
age = 10;
score = 100;
}
private:
int age;
int score;
};
void best(person *p)
{
cout << "age is " << p->age << endl;
}
int main()
{
person p1;
best(&p1);
system("pause");
return 0;
}
类做友元:
#include<iostream>
#include<string>
using namespace std;
class person {
friend class fri; //类做友元fri访问person中的私有属性
public:
person();
private:
int age;
int score;
};
//person类的构造函数在类外声明
person::person() {
age = 10;
score = 100;
}
class fri {
public:
fri();
void visit();
person *p; //要去访问的person对象
};
//fri类的构造函数在类外声明
fri::fri() {
p = new person;
}
//fri类的visit函数在类外声明
void fri::visit() {
cout << "age: " << p->age << endl;
cout << "sccore: " << p->score << endl;
}
void test()
{
fri f1;
f1.visit();
}
int main()
{
test();
system("pause");
return 0;
}
成员函数做友元:
#include <iostream>
using namespace std;
class person; //因为fri中用到person类所以需要实现声明,编译是自上而下;
class fri {
public:
fri();
void visit();
person *per;
};
class person {
friend void fri::visit(); //需要对其作用域进行定义因为不定义调用的是全局函数
public:
person();
private:
int age;
int score;
};
fri::fri() {
per = new person;
}
void fri::visit() {
cout << "age: " << per->age << endl;
}
person::person() {
age = 24;
score = 100;
}
void test()
{
fri f1;
f1.visit();
}
int main()
{
test();
system("pause");
return 0;
}
learned from:黑马程序员