友元函数是一种特殊的函数,它必须要在类中进行声明,但其本身并不是类的成员函数,但友元函数可以访问类的私有成员变量。
友元函数的好处:
1、实现类之间的数据共享
2、提高程序运行效率,方便编程
友元函数的坏处:
1、破坏数据的隐蔽性和类的封装性
2、降低了程序的可维护性
所有,友元函数应当谨慎的去使用它。
实例:
#include <iostream>
#include <cstring>
using namespace std ;
class Student
{
private :
string name ;
int age ;
char sex ;
int score ;
public :
Student(string name , int age , char sex , int score) ;
//声明友元函数
friend void display_information(Student &Stu);
};
Student::Student(string name , int age , char sex , int score)
{
this->name = name ;
this->age = age ;
this->sex = sex ;
this->score = score ;
}
//注意,友元函数不是类Student的成员,但可以访问类中的私有成员变量
void display_information(Student &Stu)
{
cout << Stu.name << endl ;
cout << Stu.age << endl ;
cout << Stu.sex << endl ;
cout << Stu.score << endl ;
}
int main(void)
{
Student STU1(\"YYX\",24,\'N\',86);
display_information(STU1);
return 0 ;
}
运行结果:
YYX
24
N
86
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对脚本之家的支持。如果你想了解更多相关内容请查看下面相关链接
继续阅读与本文标签相同的文章
上一篇 :
周鸿祎:对马化腾不记仇,偶尔也会对其朋友圈点赞
-
语音顶会Interspeech 论文解读|Constrained output embeddings for end-to-end code-switching speech recognition with only monolingual data
2026-05-18栏目: 教程
-
《Android应用开发进阶》| 每日读本书
2026-05-18栏目: 教程
-
“阿里云十年,因为有我而不同”,征文活动开始了!
2026-05-18栏目: 教程
-
玩转 Drone CI
2026-05-18栏目: 教程
-
有关阿里云对SaaS行业的思考,看这一篇就够了
2026-05-18栏目: 教程
