演示友元函数

C++C++Beginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

介绍

在本实验中,我们将学习如何在 C++ 编程语言中演示 Friend Function(友元函数)的概念。我们将创建一个带有私有成员变量的 Volume 类,并使用 Friend Function 在类外部访问这些私有变量。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL cpp(("C++")) -.-> cpp/FunctionsGroup(["Functions"]) cpp(("C++")) -.-> cpp/OOPGroup(["OOP"]) cpp/FunctionsGroup -.-> cpp/function_parameters("Function Parameters") cpp/OOPGroup -.-> cpp/classes_objects("Classes/Objects") cpp/OOPGroup -.-> cpp/access_specifiers("Access Specifiers") cpp/OOPGroup -.-> cpp/constructors("Constructors") cpp/OOPGroup -.-> cpp/encapsulation("Encapsulation") subgraph Lab Skills cpp/function_parameters -.-> lab-96140{{"演示友元函数"}} cpp/classes_objects -.-> lab-96140{{"演示友元函数"}} cpp/access_specifiers -.-> lab-96140{{"演示友元函数"}} cpp/constructors -.-> lab-96140{{"演示友元函数"}} cpp/encapsulation -.-> lab-96140{{"演示友元函数"}} end

创建 Volume

首先,在 ~/project 目录下创建一个名为 main.cpp 的 C++ 文件,并添加以下代码来定义 Volume 类:

#include <iostream>

using namespace std;

//Volume 类用于演示 C++ 中友元函数的概念
class Volume {
    //成员变量声明为私有,因此无法直接从类外部访问
    private:
        int liter;

    //使用默认构造函数将变量 liter 的值初始化为 2
    public:
        Volume(): liter(2) {}
};

我们定义了一个 Volume 类,其中包含一个私有成员变量 liter,该变量无法直接从类外部访问。

Volume 类声明 Friend Function

现在,为 Volume 类声明一个 Friend Function(友元函数),这将允许我们在类外部访问该类的私有变量。

//为 Volume 类声明友元函数
friend int mulFive(Volume);

我们声明了一个名为 mulFive()Friend Function,它接受一个 Volume 对象作为输入并返回一个整数值。

定义 Friend Function

现在,定义 mulFive() 函数,它将使用 Friend Function(友元函数)特性来访问 Volume 类的私有变量。添加以下代码来定义 mulFive() 函数:

// 定义 Volume 类使用的友元函数
int mulFive(Volume v) {
    // 友元函数允许从非成员函数访问私有数据
    v.liter *= 5;
    return v.liter;
}

我们定义了一个 mulFive() 函数,它通过 Friend Function 特性访问 Volume 类的私有变量 liter。该函数将 liter 变量乘以 5 并返回结果。

main() 函数中调用 Friend Function

main() 函数中,创建一个 Volume 类的对象,并调用 mulFive() 函数来访问和操作 Volume 类的私有数据。这是最后也是最重要的一步。

//定义 main 方法以访问类的成员
int main() {

    cout << "\n\nWelcome to LabEx :-)\n\n\n";
    cout << " =====  演示 C++ 中友元函数工作的程序  ===== \n\n";

    //声明类对象以访问类成员
    Volume vol;

    cout << "调用友元函数后的 Volume = " << mulFive(vol);

    cout << "\n\n\n";

    return 0;
}

我们定义了一个 main() 函数,它创建了一个 Volume 类的对象,并调用 mulFive() 函数来访问 Volume 类的私有数据。

总结

在本实验中,我们通过创建一个 Volume 类并使用 Friend Function(友元函数)在类外部访问该类的私有变量,学习了如何在 C++ 编程语言中演示 Friend Function 的概念。Friend Function 是一个非成员函数,它可以访问类的私有成员,在某些情况下对于操作或访问类的私有数据非常有用。