Skip to content

C++:Operator

Customizes the C++ operators for operands of user-defined types.

Three-way comparison

C++20 에 추가된 3방향 비교 연산자. 비교 객체를 반환한다.

#include <compare>
#include <iostream>

int main() {
    double foo = -0.0;
    double bar = 0.0;

    auto res = foo <=> bar;

    if (res < 0)
        std::cout << "-0 is less than 0";
    else if (res == 0)
        std::cout << "-0 and 0 are equal";
    else if (res > 0)
        std::cout << "-0 is greater than 0";
}

Type casting

class Object
{
public:
    int _id;
    operator int() { return _id; }
};

Troubleshooting

C++에서 스트림 입력 연산자 >>나 출력 연산자 <<를 오버로딩(overloading, 재지정)할 때 간혹 다음과 같은 오류가 발생하기도 한다.

ambiguous overloaded for 'operator<<'

원인은 오버로딩 함수 검색 알고리즘(overloading resolution algorithm) 때문인데, 즉 위 오류 메시지는 '컴파일러가 어떤 <<를 사용해야 할지 모호하다'는 뜻이다. 모호한 Overloading function을 수정하면 된다.

Favorite site

Prototypes

References


  1. Blog.eairship.kr-cxx-operator_overloading.pdf