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

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

友元函数的好处:

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

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对<计算机技术网(www.ctvol.com)!!>的支持。如果你想了解更多相关内容请查看下面相关链接

—-想了解关于C++友元函数的实现讲解分享!全部内容且更多的C语言教程关注<计算机技术网(www.ctvol.com)!!>

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/c-cdevelopment/482586.html

(0)
上一篇 2020年11月9日
下一篇 2020年11月9日

精彩推荐