(1)友元函数
全局函数:void setA1(A1 *p, int a1);
在类内部声明为友元函数:friend void setA1(A1 *p, int a1);
友元函数的作用:在类的内部将一个外部函数声明一个友元函数后,该外部函数调用该类对象时可以访问私有成员变量。
示例代码:
#include <iostream>
class Student
{
public:
Student()
{
grade = 60;
age = 18;
}
int GetGrade()
{
return this->grade;
}
//声明一个友元函数,这个函数是这个类的好朋友
friend void ChangeGrade(Student *p, int grade);
protected:
private:
int grade;
int age;
};
void ChangeGrade(Student *p, int grade)
{
p->grade = grade; //如果没有友元函数,将无法访问私有成员
}
int main()
{
Student stu1;
// 私有成员不可直接访问
// std::cout << stu1.grade << std::endl;
// 通过类的内部访问私有成员
std::cout << stu1.GetGrade() << std::endl; //60
//通过友元函数 修改类的私有属性
ChangeGrade(&stu1, 100);
std::cout << stu1.GetGrade() << std::endl; //100
return 0;
}
(2)友元类
如何声明:在A的内部声明B是A的友元类:friend class B;
声明位置有无要求:声明的位置 和 public private没有关系。
友元类作用:
- 若B类是A类的友员类,则B类的所有成员函数都是A类的友员函数(也就是可以通过B类的内部函数来操作A类)。
- 友员类通常设计为一种对数据操作或类之间传递消息的辅助类。
示例代码:
#include <iostream>
class Boy
{
public:
// 友元类,GirlFriend类 是 Boy的好朋友
friend class GirlFriend;
// 在GirlFriend中可以访问Boy类的私有成员 私有函数
// 声明的位置 和 public private没有关系
// 友元函数
friend void modify_salary(Boy *p, double salary);
public:
Boy(int age = 0, int face = 0)
{
this->face = face;
this->age = age;
this->asset = 0;
this->salary = 0;
this->height = 180;
}
public:
double get_asset()
{
return this->asset;
}
double get_salary()
{
return this->salary;
}
private:
double asset;
double salary;
double height;
int age;
int face;
};
void modify_salary(Boy *p, double salary)
{
p->salary = salary;
}
class GirlFriend
{
public:
GirlFriend(int age, int face):other_boy(9, 180)
{
this->age = age;
this->face = face;
}
public:
void add_boy_asset(Boy &boy, double asset)
{
boy.asset += asset; // boy是可以操作的友元对象
}
void transfer_boy_asset(Boy &boy, double asset)
{
boy.asset -= asset; // boy是可以操作的友元对象
other_boy.asset += asset; // other_boy是GirlFriend的成员
}
void print_boy_asset(Boy &boy)
{
std::cout << "boy asset=" << boy.asset << std::endl;
std::cout << "other_boy asset=" << other_boy.asset << std::endl;
}
double get_otherboy_asset()
{
return other_boy.asset;
}
private:
int age;
int face;
Boy other_boy;
};
int main()
{
// 创建一个Boy对象
Boy boy_tom(18, 8);
std::cout << boy_tom.get_asset() << std::endl; // 0
// 通过GirlFriend类来操作Boy类的属性等
GirlFriend gf(18, 6);
gf.print_boy_asset(boy_tom);
// boy asset=0
// other_boy asset=0
gf.add_boy_asset(boy_tom, 10000);
std::cout << boy_tom.get_asset() << std::endl; // 10000
std::cout << gf.get_otherboy_asset() << std::endl; // 0
gf.transfer_boy_asset(boy_tom, 5000);
gf.print_boy_asset(boy_tom);
// boy asset=5000
// other_boy asset=5000
// 通过友元函数操作Boy对象
modify_salary(&boy_tom, 3000);
std::cout << boy_tom.get_salary() << std::endl; // 3000
return 0;
}
end