在程序里,有些私有属性也想让类外特殊的一些函数或者类进行访问,就需要用到友元技术;
友元的目的就是让一个函数或者类访问另一个类中的私有成员
关键字friend
友元的三种实现:
(1)全局函数做友元
(2)类做友元
(3)成员函数做友元
class Person
{
friend void test01();//全局函数做友元;
public:
Person(int a,int b):m_a(a),m_b(b){}
int m_a;
private:
int m_b;
};
void test01()
{
Person p1(10, 20);
cout << p1.m_a << endl;
cout << p1.m_b << endl;//实现类外访问私有内容;
}
int main()
{
test01();
return 0;
}
class Person
{
friend class Student;//类做友元
public:
Person();
int m_a;
private:
int m_b;
};
class Student
{
public:
void visit();
Person p1;
};
Person::Person()
{
m_a = 10;
m_b = 20;
}
void Student::visit()
{
cout << p1.m_a << endl;
cout << p1.m_b << endl;
}
void test01()
{
Student s;
s.visit();
}
int main()
{
test01();
return 0;
}
class Person;
class Student
{
public:
void visit();
Person *p;
};
class Person
{
friend void Student::visit ();//成员函数做友元;
public:
Person();
int m_a;
private:
int m_b;
};
Person::Person()
{
m_a = 10;
m_b = 20;
}
void Student::visit()
{
p = new Person;
cout << p->m_a << endl;
cout << p->m_b << endl;
}
void test01()
{
Student s;
s.visit();
}
int main()
{
test01();
return 0;
}