C++ 연산자 오버로딩 | "+, -, *, <<" 재정의 가이드

C++ 연산자 오버로딩 | "+, -, *, <<" 재정의 가이드

이 글의 핵심

C++ 연산자 오버로딩에 대해 정리한 개발 블로그 글입니다. class Complex { private: double real, imag; public: Complex(double r = 0, double i = 0) : real(r), imag(i) {}

기본 산술 연산자

class Complex {
private:
    double real, imag;
    
public:
    Complex(double r = 0, double i = 0) : real(r), imag(i) {}
    
    // + 연산자
    Complex operator+(const Complex& other) const {
        return Complex(real + other.real, imag + other.imag);
    }
    
    // - 연산자
    Complex operator-(const Complex& other) const {
        return Complex(real - other.real, imag - other.imag);
    }
    
    void print() const {
        cout << real << " + " << imag << "i" << endl;
    }
};

int main() {
    Complex c1(3, 4);
    Complex c2(1, 2);
    Complex c3 = c1 + c2;  // operator+ 호출
    c3.print();  // 4 + 6i
}

비교 연산자

class Point {
public:
    int x, y;
    
    Point(int x, int y) : x(x), y(y) {}
    
    bool operator==(const Point& other) const {
        return x == other.x && y == other.y;
    }
    
    bool operator!=(const Point& other) const {
        return !(*this == other);
    }
    
    bool operator<(const Point& other) const {
        if (x != other.x) return x < other.x;
        return y < other.y;
    }
};

int main() {
    Point p1(1, 2);
    Point p2(1, 2);
    Point p3(2, 3);
    
    cout << (p1 == p2) << endl;  // 1 (true)
    cout << (p1 < p3) << endl;   // 1 (true)
}

입출력 연산자 (friend)

class Vector2D {
private:
    double x, y;
    
public:
    Vector2D(double x = 0, double y = 0) : x(x), y(y) {}
    
    // << 연산자 (friend 필요)
    friend ostream& operator<<(ostream& os, const Vector2D& v) {
        os << "(" << v.x << ", " << v.y << ")";
        return os;
    }
    
    // >> 연산자
    friend istream& operator>>(istream& is, Vector2D& v) {
        is >> v.x >> v.y;
        return is;
    }
};

int main() {
    Vector2D v(3.5, 4.2);
    cout << v << endl;  // (3.5, 4.2)
    
    Vector2D v2;
    cin >> v2;  // 입력: 1 2
    cout << v2 << endl;  // (1, 2)
}

실전 예시

예시 1: 분수 클래스

#include <iostream>
#include <numeric>
using namespace std;

class Fraction {
private:
    int numerator;    // 분자
    int denominator;  // 분모
    
    void simplify() {
        int gcd = std::gcd(numerator, denominator);
        numerator /= gcd;
        denominator /= gcd;
        if (denominator < 0) {
            numerator = -numerator;
            denominator = -denominator;
        }
    }
    
public:
    Fraction(int n = 0, int d = 1) : numerator(n), denominator(d) {
        if (d == 0) throw invalid_argument("분모는 0이 될 수 없습니다");
        simplify();
    }
    
    Fraction operator+(const Fraction& other) const {
        return Fraction(
            numerator * other.denominator + other.numerator * denominator,
            denominator * other.denominator
        );
    }
    
    Fraction operator-(const Fraction& other) const {
        return Fraction(
            numerator * other.denominator - other.numerator * denominator,
            denominator * other.denominator
        );
    }
    
    Fraction operator*(const Fraction& other) const {
        return Fraction(
            numerator * other.numerator,
            denominator * other.denominator
        );
    }
    
    Fraction operator/(const Fraction& other) const {
        return Fraction(
            numerator * other.denominator,
            denominator * other.numerator
        );
    }
    
    bool operator==(const Fraction& other) const {
        return numerator == other.numerator && denominator == other.denominator;
    }
    
    friend ostream& operator<<(ostream& os, const Fraction& f) {
        if (f.denominator == 1) {
            os << f.numerator;
        } else {
            os << f.numerator << "/" << f.denominator;
        }
        return os;
    }
};

int main() {
    Fraction f1(1, 2);  // 1/2
    Fraction f2(1, 3);  // 1/3
    
    cout << f1 << " + " << f2 << " = " << (f1 + f2) << endl;  // 5/6
    cout << f1 << " * " << f2 << " = " << (f1 * f2) << endl;  // 1/6
    
    return 0;
}

설명: 연산자 오버로딩으로 분수 연산을 직관적으로 표현할 수 있습니다.

예시 2: 행렬 클래스

#include <iostream>
#include <vector>
using namespace std;

class Matrix {
private:
    vector<vector<int>> data;
    int rows, cols;
    
public:
    Matrix(int r, int c) : rows(r), cols(c) {
        data.resize(r, vector<int>(c, 0));
    }
    
    int& operator()(int r, int c) {
        return data[r][c];
    }
    
    Matrix operator+(const Matrix& other) const {
        if (rows != other.rows || cols != other.cols) {
            throw invalid_argument("행렬 크기가 다릅니다");
        }
        
        Matrix result(rows, cols);
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                result.data[i][j] = data[i][j] + other.data[i][j];
            }
        }
        return result;
    }
    
    Matrix operator*(const Matrix& other) const {
        if (cols != other.rows) {
            throw invalid_argument("행렬 곱셈 불가");
        }
        
        Matrix result(rows, other.cols);
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < other.cols; j++) {
                for (int k = 0; k < cols; k++) {
                    result.data[i][j] += data[i][k] * other.data[k][j];
                }
            }
        }
        return result;
    }
    
    friend ostream& operator<<(ostream& os, const Matrix& m) {
        for (int i = 0; i < m.rows; i++) {
            for (int j = 0; j < m.cols; j++) {
                os << m.data[i][j] << " ";
            }
            os << endl;
        }
        return os;
    }
};

int main() {
    Matrix m1(2, 2);
    m1(0, 0) = 1; m1(0, 1) = 2;
    m1(1, 0) = 3; m1(1, 1) = 4;
    
    Matrix m2(2, 2);
    m2(0, 0) = 5; m2(0, 1) = 6;
    m2(1, 0) = 7; m2(1, 1) = 8;
    
    cout << "m1 + m2:" << endl << (m1 + m2) << endl;
    cout << "m1 * m2:" << endl << (m1 * m2) << endl;
    
    return 0;
}

설명: () 연산자로 행렬 원소 접근을 직관적으로 만들고, +와 * 연산자로 행렬 연산을 구현합니다.

예시 3: 스마트 문자열 클래스

#include <iostream>
#include <cstring>
using namespace std;

class String {
private:
    char* data;
    size_t length;
    
public:
    String(const char* str = "") {
        length = strlen(str);
        data = new char[length + 1];
        strcpy(data, str);
    }
    
    ~String() {
        delete[] data;
    }
    
    // 복사 생성자
    String(const String& other) {
        length = other.length;
        data = new char[length + 1];
        strcpy(data, other.data);
    }
    
    // 대입 연산자
    String& operator=(const String& other) {
        if (this != &other) {
            delete[] data;
            length = other.length;
            data = new char[length + 1];
            strcpy(data, other.data);
        }
        return *this;
    }
    
    // + 연산자 (문자열 연결)
    String operator+(const String& other) const {
        char* temp = new char[length + other.length + 1];
        strcpy(temp, data);
        strcat(temp, other.data);
        String result(temp);
        delete[] temp;
        return result;
    }
    
    // [] 연산자
    char& operator {
        return data[index];
    }
    
    // == 연산자
    bool operator==(const String& other) const {
        return strcmp(data, other.data) == 0;
    }
    
    friend ostream& operator<<(ostream& os, const String& str) {
        os << str.data;
        return os;
    }
};

int main() {
    String s1("Hello");
    String s2(" World");
    String s3 = s1 + s2;
    
    cout << s3 << endl;  // Hello World
    cout << s3[0] << endl;  // H
    
    return 0;
}

설명: 문자열 클래스에 연산자 오버로딩을 적용하여 사용성을 높입니다.

자주 발생하는 문제

문제 1: 대입 연산자에서 자기 대입 체크 누락

증상: 자기 자신을 대입하면 크래시

원인: delete 후 복사 시도

해결법:

// ❌ 위험한 코드
String& operator=(const String& other) {
    delete[] data;  // 자기 자신이면 문제!
    data = new char[other.length + 1];
    strcpy(data, other.data);
    return *this;
}

// ✅ 자기 대입 체크
String& operator=(const String& other) {
    if (this != &other) {  // 자기 대입 체크
        delete[] data;
        data = new char[other.length + 1];
        strcpy(data, other.data);
    }
    return *this;
}

문제 2: const 정확성

증상: const 객체에서 연산자 호출 불가

원인: const 키워드 누락

해결법:

// ❌ const 객체에서 호출 불가
Complex operator+(const Complex& other) {
    return Complex(real + other.real, imag + other.imag);
}

// ✅ const 멤버 함수
Complex operator+(const Complex& other) const {
    return Complex(real + other.real, imag + other.imag);
}

문제 3: 연산자 우선순위 무시

증상: 예상과 다른 결과

원인: 연산자 우선순위 오해

해결법:

// 연산자 우선순위는 변경 불가
// 괄호로 명확하게 표현
Complex c = (a + b) * c;  // 명확

FAQ

Q1: 모든 연산자를 오버로딩할 수 있나요?

A: 아니요, 일부는 불가능합니다.

  • 오버로딩 불가: ::, ., .*, ?:, sizeof
  • 오버로딩 가능: +, -, *, /, ==, <<, []

Q2: friend는 왜 필요한가요?

A: <<, >> 같은 연산자는 왼쪽 피연산자가 ostream/istream이므로 멤버 함수로 만들 수 없습니다.

Q3: 연산자 오버로딩은 언제 사용하나요?

A:

  • 수학적 객체 (벡터, 행렬, 복소수)
  • 컨테이너 (배열, 리스트)
  • 스마트 포인터

Q4: 성능에 영향이 있나요?

A: 인라인화되면 오버헤드가 거의 없습니다. 컴파일러가 최적화합니다.

Q5: ++a vs a++는 어떻게 구현하나요?

A:

// 전위 증가
T& operator++() {
    // 증가
    return *this;
}

// 후위 증가 (int는 더미 매개변수)
T operator++(int) {
    T temp = *this;
    ++(*this);
    return temp;
}

Q6: 연산자 오버로딩 남용은?

A: 직관적이지 않은 연산자 오버로딩은 피하세요. 예: +를 파일 삭제에 사용하는 것은 나쁜 예입니다.


같이 보면 좋은 글 (내부 링크)

이 주제와 연결되는 다른 글입니다.

  • C++ 연산자 우선순위 | “Operator Precedence” 가이드
  • C++ ADL | “Argument Dependent Lookup” 가이드
  • C++ User-Defined Literals | “사용자 정의 리터럴” 가이드

관련 글

  • C++ 연산자 우선순위 |
  • C++ ADL |
  • C++ 함수 객체 |
  • C++ User-Defined Literals |
  • 배열과 리스트 | 코딩 테스트 필수 자료구조 완벽 정리