C++ 方法重载

C++Beginner
立即练习

介绍

在本实验中,我们将学习如何在 C++ 编程语言中演示方法重载(Method Overloading)的概念。方法重载是一种允许我们在一个类中定义多个同名方法或函数,但这些方法的参数列表不同的概念。在方法调用时,根据传递的参数数量和类型,系统会自动调用合适的方法。

创建 C++ 文件

首先,我们使用以下命令在 ~/project 目录下创建一个名为 main.cpp 的 C++ 文件:

touch ~/project/main.cpp

编写代码

我们将创建一个名为 shape 的类,并定义两个名为 area() 的方法,但它们的参数数量不同。input() 方法将从用户那里获取输入,以设置成员变量 lbs 的值。然后,我们将定义 main() 方法,以便从类外部访问 shape 类的成员。

#include <iostream>

using namespace std;

class shape {

    //声明成员变量
    public:
        int l, b, s;

    //定义成员函数或方法
    public:
        void input() {
            cout << "Enter the length of each side of the Square: \n";
            cin >> s;
            cout << "\n";
            cout << "Enter the length and breadth of the Rectangle: \n";
            cin >> l >> b;
            cout << "\n";
        }

    //演示方法重载
    public:
        void area(int side) {
            cout << "Area of Square = " << side * side << endl;
        }

        void area(int length, int breadth) {
            cout << "Area of Rectangle = " << length * breadth << endl;
        }
};

int main() {
    cout << "\n\nWelcome to LabEx :-)\n\n\n";
    cout << " =====  Program to demonstrate Method Overloading in a Class, in CPP  ===== \n\n";

    //声明类对象以从类外部访问类成员
    shape sh;

    cout << "\nCalling the input() function to take the values from the user\n";
    sh.input();

    cout << "\nCalling the area(int) function to calculate the area of the Square\n";
    sh.area(sh.s);

    cout << "\nCalling the area(int,int) function to calculate the area of the Rectangle\n";
    sh.area(sh.l, sh.b);

    cout << "\nExiting the main() method\n\n\n";

    return 0;
}

编译并运行代码

我们现在将使用以下命令编译并运行代码:

g++ main.cpp -o main && ./main

理解输出

程序的输出如下:

Welcome to LabEx :-)


 =====  Program to demonstrate Method Overloading in a Class, in CPP  =====

Calling the input() function to take the values from the user
Enter the length of each side of the Square:
4

Enter the length and breadth of the Rectangle:
5
6


Calling the area(int) function to calculate the area of the Square
Area of Square = 16

Calling the area(int,int) function to calculate the area of the Rectangle
Area of Rectangle = 30

Exiting the main() method

在这里,我们可以看到 input() 方法被调用来接收用户输入。然后,带有一个参数的 area() 方法被调用来计算正方形的面积,而带有两个参数的 area() 方法被调用来计算矩形的面积。

总结

在本实验中,我们学习了如何在 C++ 编程语言中使用方法重载(Method Overloading)的概念。我们创建了一个程序,定义了一个名为 shape 的类,其中包含两个名为 area() 的方法,但它们的参数数量不同,从而实现了方法重载。用户输入了矩形的长和宽以及正方形的边长。我们使用重载的方法计算了两种形状的面积。