C++ 메서드 오버로딩

C++Beginner
지금 연습하기

소개

이 랩에서는 C++ 프로그래밍 언어에서 메서드 오버로딩 (Method Overloading) 의 개념을 시연하는 방법을 배웁니다. 메서드 오버로딩은 클래스 내에서 동일한 이름을 가진 여러 메서드 또는 함수를 가질 수 있지만, 매개변수가 다른 개념입니다. 적절한 메서드는 메서드 호출 시 전달된 매개변수의 수와 유형에 따라 호출됩니다.

C++ 파일 생성

먼저, 다음 명령을 사용하여 ~/project 디렉토리에 main.cpp라는 새 C++ 파일을 생성합니다.

touch ~/project/main.cpp

코드 작성

shape라는 클래스를 생성하고 area()라는 두 개의 메서드를 정의하지만, 매개변수의 수가 다르게 정의합니다. input() 메서드는 사용자로부터 입력을 받아 멤버 변수 l, b, 및 s의 값을 설정합니다. 그런 다음 main() 메서드를 정의하여 클래스 외부에서 shape 클래스의 멤버에 접근합니다.

#include <iostream>

using namespace std;

class shape {

    //declaring member variables
    public:
        int l, b, s;

    //defining member functions or methods
    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";
        }

    //Demonstrating Method Overloading
    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";

    //Declaring class object to access class members from outside the class
    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()라는 두 개의 메서드가 있지만, 매개변수의 수가 달라서 오버로딩되었습니다. 사용자는 직사각형의 길이와 너비, 그리고 정사각형의 한 변의 길이를 입력합니다. 오버로딩된 메서드를 사용하여 두 도형의 면적을 계산했습니다.