SW개발/C++

7장. 연산자 다중 정의

코코도롱 2025. 3. 5. 21:24
반응형
  • 연산자 다중 정의: 기존 연산자를 클래스에 맞게 재정의하는 기능
  • 연산자 함수: operator 키워드를 사용하여 연산자 동작을 정의하는 함수
  • 연산자 다중 정의는 코드의 가독성을 높이고, 사용자 정의 타입을 더 자연스럽게 사용할 수 있도록 지원

7.1 연산자 함수란?

  • operator+, operator- 등의 형태로 연산자 정의 가능
  • 멤버 함수 또는 비멤버 함수로 정의 가능
  • 연산자 오버로딩 시 적절한 반환 타입과 매개변수를 설정해야 함
class Vector {
    int x, y;
public:
    Vector(int a, int b) : x(a), y(b) {}
    Vector operator+(const Vector& other) const {
        return Vector(x + other.x, y + other.y);
    }
};

7.2 단순 대입 연산자

  • operator=를 재정의하여 깊은 복사 수행 가능
  • 기본 대입 연산자는 얕은 복사를 수행
  • 동적 할당을 사용하는 경우 반드시 메모리 해제 후 새롭게 할당해야 함
class Example {
    int* data;
public:
    Example& operator=(const Example& other) {
        if (this != &other) {
            delete data;
            data = new int(*other.data);
        }
        return *this;
    }
};

7.3 함수 호출 연산자

  • operator()를 재정의하여 객체를 함수처럼 호출 가능
  • 람다 함수처럼 사용 가능하며, 함수 객체(Functor) 구현 시 유용
class Functor {
public:
    void operator()(int x) {
        cout << "Value: " << x << endl;
    }
};

7.4 배열 연산자

  • operator[]를 재정의하여 배열처럼 접근 가능
  • 읽기 전용 접근을 위해 const 버전도 제공해야 함
class Array {
    int data[10];
public:
    int& operator[](int index) { return data[index]; }
    const int& operator[](int index) const { return data[index]; }
};

7.5 관계 연산자

  • operator==, operator!=, operator< 등을 재정의하여 객체 비교 가능
  • 비교 연산자는 bool 타입을 반환하도록 설계
class Compare {
    int value;
public:
    bool operator==(const Compare& other) const { return value == other.value; }
};

7.6 단항 증감 연산자

  • operator++, operator--를 재정의하여 객체의 상태 변화 가능
  • 전위/후위 연산자 오버로딩 시 반환 방식 주의
class Counter {
    int count;
public:
    Counter& operator++() { ++count; return *this; } // 전위 증가
    Counter operator++(int) { Counter temp = *this; ++count; return temp; } // 후위 증가
};
반응형