IT评测·应用市场-qidao123.com

标题: cpp-友元 [打印本页]

作者: 李优秀    时间: 2025-3-24 12:03
标题: cpp-友元
理解 C++ 中的友元(Friend)
在 C++ 语言中,封装(Encapsulation) 是面向对象编程的重要特性之一。它允许类将数据隐藏在私有(private)或受掩护(protected)成员中,防止外部直接访问。然而,在某些情况下,我们希望某些函数或类能够访问这些私有成员,而不粉碎封装性。这时,我们就需要友元(Friend)

1. 什么是友元?

友元(friend) 是 C++ 提供的一种机制,它允许一个函数或另一个类访问某个类的私有和受掩护成员。友元有三种类型:

2. 友元函数

友元函数是一个非成员函数,但它可以访问类的私有和受掩护成员。要声明友元函数,需要在类内部利用 friend 关键字。
示例:友元函数

  1. #include <iostream>
  2. using namespace std;
  3. class Box {
  4. private:
  5.     double width;
  6. public:
  7.     Box(double w) : width(w) {}
  8.    
  9.     // 声明友元函数
  10.     friend void printWidth(const Box &b);
  11. };
  12. // 定义友元函数
  13. void printWidth(const Box &b) {
  14.     cout << "Width: " << b.width << endl;
  15. }
  16. int main() {
  17.     Box b(10.5);
  18.     printWidth(b);
  19.     return 0;
  20. }
复制代码
在上面的示例中,printWidth 不是 Box 类的成员函数,但由于它被声明为 friend,它可以访问 Box 的私有成员 width。

3. 友元类

友元类允许一个类访问另一个类的私有和受掩护成员。
示例:友元类

  1. #include <iostream>
  2. using namespace std;
  3. class Engine {
  4. private:
  5.     int horsepower;
  6. public:
  7.     Engine(int hp) : horsepower(hp) {}
  8.    
  9.     // 声明 Car 为友元类
  10.     friend class Car;
  11. };
  12. class Car {
  13. public:
  14.     void showEnginePower(const Engine &e) {
  15.         cout << "Engine horsepower: " << e.horsepower << endl;
  16.     }
  17. };
  18. int main() {
  19.     Engine e(150);
  20.     Car c;
  21.     c.showEnginePower(e);
  22.     return 0;
  23. }
复制代码
在这个例子中,Car 是 Engine 的友元类,因此它可以访问 Engine 类的私有成员 horsepower。

4. 友元成员函数

我们还可以只将另一个类的某个成员函数设为友元,而不是整个类。
示例:友元成员函数

  1. #include <iostream>
  2. using namespace std;
  3. class Engine;
  4. class Car {
  5. public:
  6.     void showEnginePower(const Engine &e);
  7. };
  8. class Engine {
  9. private:
  10.     int horsepower;
  11. public:
  12.     Engine(int hp) : horsepower(hp) {}
  13.    
  14.     // 声明 Car::showEnginePower 为友元
  15.     friend void Car::showEnginePower(const Engine &e);
  16. };
  17. void Car::showEnginePower(const Engine &e) {
  18.     cout << "Engine horsepower: " << e.horsepower << endl;
  19. }
  20. int main() {
  21.     Engine e(200);
  22.     Car c;
  23.     c.showEnginePower(e);
  24.     return 0;
  25. }
复制代码
这里 Car::showEnginePower 是 Engine 的友元成员函数,因此它可以访问 Engine 的私有成员。

5. 友元的应用场景

友元在以下情况中非常有效:

6. 友元的优缺点

优点:


缺点:



7. 总结


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 IT评测·应用市场-qidao123.com (https://dis.qidao123.com/) Powered by Discuz! X3.4