友元函数是一种特殊的函数,它必须要在类中进行声明,但其本身并不是类的成员函数,但友元函数可以访问类的私有成员变量。
友元函数的好处:
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
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对武林网的支持。如果你想了解更多相关内容请查看下面相关链接
新闻热点
疑难解答
图片精选