C++ 中友元函数的优缺点

2024 年 8 月 28 日 | 3 分钟阅读

我们创建友元函数是为了在 C++ 面向对象编程系统中访问不同的修饰符,例如 Protected、Private 和 Public。友元函数或友元类通常在类的外部定义,但仍然可以访问类代码中定义的类的私有(private)、保护(protected)和公共(public)成员。

优点缺点
声明可以放在代码的任何位置它不会被传递给派生类
调用它时无需创建对象。它们没有存储指定类。
也可以使用友元函数访问类的非公有成员。当多个类关联在一起时,友元函数非常有用。
它可以添加额外的功能。允许将私有和保护成员显示为类的信息。
使编程体验比以往任何时候都更高效。它可以在其定义的同一个类中同时拥有公有和私有保护成员。

C++ 代码

输出

/tmp /mB gjSey FC Z.o
3135

C++ 代码

输出

/tmp /mB gjSey FC Z.o
After performing the operations, the value for X we have got is 3979

C++ 代码

输出

/tmp /mB gjSey FC Z.o
Dear User, please enter the value for the variable first no: 35
Dear User, please enter the value for the variable second no: 365
Hey! User, the maximum number among the inputs entered by you is: 365

下一个主题C++ 预处理器