C++ 연산자 오버로딩 (+)

C++Beginner
지금 연습하기

소개

이 랩에서는 C++ 프로그래밍 언어에서 + 연산자 오버로딩 (operator overloading) 개념을 시연하는 방법을 배우게 됩니다. 연산자 오버로딩은 C++ 의 기능으로, 사용되는 컨텍스트에 따라 단일 연산자 또는 기호를 다른 의미로 사용할 수 있도록 합니다. 이 랩에서는 + 연산자를 사용하여 두 개의 Cuboid 객체를 더하는 방법을 보여줍니다.

새 C++ 파일 생성

~/project 디렉토리에 main.cpp라는 이름의 새로운 C++ 파일을 생성합니다.

cd ~/project
touch main.cpp

+ 연산자 오버로딩을 시연하는 코드 작성

3 차원 직육면체를 나타내는 Cuboid 클래스를 생성하기 위해 다음 코드를 main.cpp에 추가합니다.

#include <iostream>

using namespace std;

// CPP 에서 Plus 연산자 오버로딩 개념을 시연하기 위해 Cuboid 클래스 정의
class Cuboid {
    // 클래스 외부에서 접근하기 위해 클래스 멤버 변수를 public 으로 선언
    public:
        double length; // Cuboid 의 길이
        double breadth; // Cuboid 의 너비
        double height; // Cuboid 의 높이

        public:
        double getVolume(void) {
            return length * breadth * height;
        }
        void setLength(double l) {
            length = l;
        }

        void setBreadth(double b) {
            breadth = b;
        }

        void setHeight(double h) {
            height = h;
        }

        // 두 Cuboid 객체를 서로 더하기 위해 + 연산자 오버로딩
        Cuboid operator + (const Cuboid & c) {
            Cuboid cuboid;
            cuboid.length = this -> length + c.length;
            cuboid.breadth = this -> breadth + c.breadth;
            cuboid.height = this -> height + c.height;
            return cuboid;
        }
};

main 함수 정의

세 개의 Cuboid 객체를 생성하고, 치수를 설정하고, 부피를 계산하고, 두 객체를 더하고, 결과 직육면체 객체의 치수와 부피를 출력하는 main 함수를 구현하기 위해 다음 코드를 main.cpp에 추가합니다.

// 클래스 멤버에 접근하기 위해 main 메서드 정의
int main() {

    cout << "\n\nWelcome to LabEx :-)\n\n\n";
    cout << " =====  Program to demonstrate the Plus Operator Overloading, in CPP  ===== \n\n";

    // 클래스 멤버에 접근하기 위해 클래스 객체 선언
    Cuboid c1;
    Cuboid c2;
    Cuboid c3;

    // Cuboid 의 부피를 저장하기 위해
    double volume = 0.0;

    // 첫 번째 Cuboid 객체: c1 의 길이, 너비 및 높이 설정
    c1.setLength(3.0);
    c1.setBreadth(4.0);
    c1.setHeight(5.0);

    // 두 번째 Cuboid 객체: c2 의 길이, 너비 및 높이 설정
    c2.setLength(2.0);
    c2.setBreadth(5.0);
    c2.setHeight(8.0);

    // 첫 번째 Cuboid 의 부피 찾기: c1
    cout << "getVolume() 메서드를 호출하여 Cuboid c1 의 부피를 찾습니다\n";
    volume = c1.getVolume();
    cout << "Cuboid c1 의 부피는 : " << volume << "\n\n\n";

    // 첫 번째 Cuboid 의 부피 찾기: c1
    cout << "getVolume() 메서드를 호출하여 Cuboid c2 의 부피를 찾습니다\n";
    volume = c2.getVolume();
    cout << "Cuboid c2 의 부피는 : " << volume << "\n\n\n";

    // 두 Cuboid 객체 c1 과 c2 를 더하여 세 번째 객체 c3 을 형성:
    c3 = c1 + c2;

    // 세 번째 Cuboid 의 치수 출력: c3
    cout << "Cuboid c3 의 길이는 : " << c3.length << endl;
    cout << "Cuboid c3 의 너비는 : " << c3.breadth << endl;
    cout << "Cuboid c3 의 높이는 : " << c3.height << endl;

    // 세 번째 Cuboid 의 부피 찾기: c3
    cout << "\n\ngetVolume() 메서드를 호출하여 Cuboid c3 의 부피를 찾습니다\n";
    volume = c3.getVolume();
    cout << "Cuboid c3 의 부피는 : " << volume << endl;
    cout << "\n\n\n";

    return 0;
}

코드 컴파일 및 실행

다음 명령을 사용하여 코드를 컴파일하고 실행합니다.

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

다음과 같은 출력을 볼 수 있습니다.

Welcome to LabEx :-)


 =====  Program to demonstrate the Plus Operator Overloading, in CPP  =====

Calling the getVolume() method to find the volume of Cuboid c1
Volume of the Cuboid c1 is : 60



Calling the getVolume() method to find the volume of Cuboid c2
Volume of the Cuboid c2 is : 80



Length of the Cuboid c3 is : 5
Breadth of the Cuboid c3 is : 9
Height of the Cuboid c3 is : 13


Calling the getVolume() method to find the volume of Cuboid c3
Volume of the Cuboid c3 is : 585

요약

이 랩에서는 C++ 프로그래밍 언어에서 + 연산자 오버로딩 (Operator Overloading) 의 개념을 시연하는 방법을 배웠습니다. 연산자 오버로딩은 C++ 의 강력하고 유용한 기능으로, 서로 다른 컨텍스트에서 서로 다른 의미로 연산자를 사용할 수 있게 해줍니다. + 연산자를 오버로딩함으로써 두 개의 Cuboid 객체를 서로 더할 수 있습니다.