C++友元函数实现

xiaoxiao2021-02-28  115

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

友元函数的好处:

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

Engineer-Bruce_Yang 认证博客专家 嵌入式硬件 单片机 arm开发 本科毕业于华南理工大学,现美国卡罗尔工商管理硕士研究生在读,曾就职于世界名企伟易达、联发科技等,多年嵌入式产品开发经验,在智能玩具、安防产品、平板电脑、手机开发有丰富的实战开发经验,现任深圳市云之手科技有限公司副总经理、研发总工程师。
转载请注明原文地址: https://www.6miu.com/read-59346.html

最新回复(0)