Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does an operator inside a class work?

class A {
public:
    string operator+( const A& rhs ) {
        return "this and A&";
    }
};

string operator+( const A& lhs, const A& rhs ) {
    return "A& and A&";
}

string operator-( const A& lhs, const A& rhs ) {
    return "A& and A&";
}

int main() {
    A a;
    cout << "a+a = " << a + a << endl;
    cout << "a-a = " << a - a << endl;
    return 0;
}

//output
a+a = this and A&
a-a = A& and A&

I'm curious as to why the operator inside the class gets to be called rather than the outside one. Is there some sort of priority among operators?

like image 367
hjjg200 Avatar asked Nov 03 '16 09:11

hjjg200


People also ask

How does operator function work?

A function operator is a function that takes one (or more) functions as input and returns a function as output. In some ways, function operators are similar to functionals: there's nothing you can't do without them, but they can make your code more readable and expressive, and they can help you write code faster.

What are the rules of operator?

Rules for operator overloading in C++Only built-in operators can be overloaded. If some operators are not present in C++, we cannot overload them. The precedence of the operators remains same. The overloaded operator cannot hold the default parameters except function call operator “()”.

Can we overload == operator?

Overloading Binary Operators Suppose that we wish to overload the binary operator == to compare two Point objects. We could do it as a member function or non-member function. To overload as a member function, the declaration is as follows: class Point { public: bool operator==(const Point & rhs) const; // p1.


1 Answers

The process of selecting amongst several functions of the same name is called overload resolution. In this code, the member is preferred because the non-member requires a qualification conversion (adding const to lhs) but the member does not. If you made the member function const (which you should, since it does not modify *this) then it would be ambiguous.

like image 158
Bathsheba Avatar answered Oct 20 '22 00:10

Bathsheba