#cpp Operators Overload 간단히 정리

1 minute read

웹 서핑 중에 간단히 잘 정리된 사이트를 찾아서 가물가물 하던 터에 한번 정리해봤다.

Assignment Operator =

MyClass& operator=(const MyClass& rhs)
{
    // check for self-assignment
    if (this == &rhs)       return *this;

    // 어쩌구 저쩌구

    return *this;
}

자기를 자기 자신에게 대입(self-assignment)하는지 검사하는 버릇을 들여야 한다. 메모리 할당, 해제를 하는 클래스는 self-assignment 검사를 안 해주면 저기서 안 죽고 엉뚱한 곳에서 터지는 버그로 고생할 수 있다. 프로그램이 저기서 잘 죽어 주기만을 빌어야 한다.

리턴 값이 const-reference가 아니라서 좀 이상할 수 있는데, 이딴 식의 대입을 지원하기 위해서이다. primitive type은 다 이런 대입을 지원하니, 내가 정의한 클래스도 지원해주도록 한다.

MyClass a,b,c;
(a=b)=c;

Compound Assignment Operators += -= *=

MyClass& MyClass::operator+=(const MyClass& rhs)
{
    // 어쩌구 저쩌구

    return *this;
}

리턴 값이 const-reference가 아닌 이유는 Assignment Operator=에서 설명한 것과 같다.

MyClass a,b,c;
(a+=b)+=c;

이런게 될지는 생각도 못해봤네.

Binary Arithmetic Operators + - *

const MyClass MyClass::operator+(const MyClass& other) const
{
    MyClass result = *this; // or MyClass result(*this);
    result += other;
    return result;
}
const MyClass MyClass::operator+(const MyClass& other) const
{
    return MyClass(*this) += other;
}

Compound Assignment Operator를 사용해서 간단히 구현할 수 있다.

Comparison Operators == !=

bool MyClass::operator!=(const MyClass& other) const
{
    return !(*this == other);
}

당연히 operator== 하나만 구현하면 operator!=는 쉽게 구현 가능하다.

참고 : C++ Operator Overloading Guidelines