Skip to content
Search

C++:Operator

lastmod 2020-07-24created 2015-04-0611 edits

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

Three-way comparison

The three-way comparison operator added in C++20. Returns a comparison object.

#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

In C++, when overloading the stream input operator >> or output operator <<, the following error sometimes occurs.

ambiguous overloaded for 'operator<<'

The cause is the overloading resolution algorithm; the error message above means 'the compiler cannot tell which << to use'. Fix the ambiguous overloading function.

Favorite site

Prototypes

References


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

author Zer0 sitemap