一、友元的概述
- 友元依靠关键字friend进行声明。
- friend关键字只出现在声明处 。
- 其他类、类成员函数、全局函数都可声明为友元 友元函数。
- 友元不是类的成员,不带this指针 。
- 友元函数可访问对象任意成员属性,包括私有属性。
二、全局函数做友元
全局函数作友元的方法:定义一个全局函数,将其在类内声明(前面加上关键字friend),此时该全局函数就成了这个类的友元,可以访问类内的全部属性
#include <iostream>
#include <string>
using namespace std;
class student {
friend void setnum(student &stu);
public:
int age;
private:
int num;
};
void setnum(student &stu)
{
stu.num =10;
cout<<"私有属性num的值为:"<<stu.num<<endl;
}
void test1()
{
student stu_1;
setnum(stu_1);
}
int main()
{
test1();
system("pause");
}
三、类作友元
类作友元的方法:定义一个类,将其在另一个类内声明(前面加上关键字friend),此时前一个类就成了后一个类的友元,可以访问类内的全部属性。
#include <iostream>
#include <string>
using namespace std;
class student {
friend class teacher;
friend void test1();
public:
int age;
private:
int score;
};
class teacher{
public:
void setscore(student &stu)
{
stu.score=100;
}
};
void test1()
{
student stu_1;
teacher tea_1;
tea_1.setscore(stu_1);
cout << "老师类做友元修改学生的私有属性score为:"<<stu_1.score<<endl;
}
int main()
{
test1();
system("pause");
}
四、使用成员函数作友元
使用成员函数作友元方法和前两个大同小异,这里的关键是由类的定义顺序造成的前一个类的成员函数无法访问后一个类的属性。这里采用的方法是提前声明后面的类。对于成员函数无法访问到后一个类的成员,可以先将该成员函数声明,再在所有类定义完之后再进行定义。
#include <iostream>
#include <string>
using namespace std;
class student;
class teacher{
public:
teacher();
student *stu_1;
~teacher()
{
delete stu_1;
}
};
class student {
friend teacher::teacher();
public:
int age;
~student();
private:
int score;
};
teacher::teacher()
{
stu_1=new student;
stu_1->score=100;
cout<<"stu_1的私有属性score为:"<<stu_1->score<<endl;
}
void test1()
{
teacher tea_1;
}
int main()
{
test1();
system("pause");
}