C, C++

[C++] 연산자 오버로딩 (Operator Overloading): 개념, 구현 방법 (friend function에서, method function에서), 주의사항

깃짱 2024. 5. 10. 08:00
반응형
반응형

 

💋 연산자 오버로딩이란?

✔️ 개념

C++에서 연산자 오버로딩(operator overloading)은 클래스 또는 structure에서 기존 연산자인 +, - , =, ==, *, /, % 등등을 재정의하는 것을 말합니다. 객체들에 대한 연산자 사용이 가능해져, 코드의 가독성과 재사용성을 높일 수 있습니다.

✔️ 구조

ReturnType operatorOP (arguments) {
    // 구현
}
  • OP는 오버로드하고자 하는 연산자
    • 보통 + 연산자의 이름은 + 그 자체임.
  • ReturnType은 연산 결과의 타입
  • arguments는 연산자의 피연산자

연산자 오버로딩은 보통 멤버 함수나 friend 함수을 통해 구현됩니다.

💋 구현 방법

✔️ friend function에서 오버로딩

#include <iostream>

class Complex {
public:
    double real;
    double imag;

    Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {}

    // 외부에서 사용할 수 있도록 friend function 선언
    friend Complex operator+(const Complex& a, const Complex& b);
    friend bool operator==(const Complex& a, const Complex& b);
};

// 덧셈 연산자 오버로딩, 클래스 외부 friend function에서 정의
Complex operator+(const Complex& a, const Complex& b) {
    return Complex(a.real + b.real, a.imag + b.imag);
}

// 비교 연산자 오버로딩, 클래스 외부 friend function에서 정의
bool operator==(const Complex& a, const Complex& b) {
    return a.real == b.real && a.imag == b.imag;
}

int main() {
    Complex c1(1.0, 2.0), c2(2.0, 3.0);
    Complex c3 = c1 + c2;
    std::cout << "Result: " << c3.real << " + " << c3.imag << "i\n";

    if (c1 == c2) {
        std::cout << "c1 and c2 are equal\n";
    } else {
        std::cout << "c1 and c2 are not equal\n";
    }

    return 0;
}

✔️ member function에서 오버로딩

x + y를 오버로딩한다고 할 때, x는 calling object가 된다.

#include <iostream>

class Complex {
public:
    double real;
    double imag;

    Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {}

    // 덧셈 연산자 오버로딩
    Complex operator+(const Complex& other) {
        return Complex(real + other.real, imag + other.imag);
    }

    // 비교 연산자 오버로딩
    bool operator==(const Complex& other) const {
        return real == other.real && imag == other.imag;
    }
};

int main() {
    Complex c1(1.0, 2.0), c2(2.0, 3.0);
    Complex c3 = c1 + c2;
    std::cout << "Result: " << c3.real << " + " << c3.imag << "i\\n";

    if (c1 == c2) {
        std::cout << "c1 and c2 are equal\\n";
    } else {
        std::cout << "c1 and c2 are not equal\\n";
    }

    return 0;
}

💋 주의사항

✔️ +, -는 파라미터가 2개일수도, 1개일수도?

실제로는 이 두가지가 모두 사용된다.

z = x + y // binary operator +
z = -x // unary operator +

이 두 가지는 파라미터의 개수가 다르다. 따라서 이름만 같을 뿐 각자 다른 함수로 오버로딩 된다.

(클래스 외부 friend function에서 + 연산자를 오버로딩 하는 경우)

const Money operator +(const Money& amount1, const Money& amount2);
const Money operator +(const Money& amount); // unary operator +

 

 

도움이 되었다면, 공감/댓글을 달아주면 깃짱에게 큰 힘이 됩니다!🌟
비밀댓글과 메일을 통해 오는 개인적인 질문은 받지 않고 있습니다. 꼭 공개댓글로 남겨주세요!

 

반응형