关于C++友元函数的实现讲解

今天小编就为大家分享一篇关于关于C++友元函数的实现讲解,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧

友元函数是一种特殊的函数,它必须要在类中进行声明,但其本身并不是类的成员函数,但友元函数可以访问类的私有成员变量。

友元函数的好处:

1、实现类之间的数据共享

2、提高程序运行效率,方便编程

友元函数的坏处:

1、破坏数据的隐蔽性和类的封装性

2、降低了程序的可维护性

所有,友元函数应当谨慎的去使用它。

实例:

 #include  #include  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

总结

以上就是关于C++友元函数的实现讲解的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » C语言