When the internal operator is used and when the external

Let's say I defined a class with an internal operator +as well as an external operator +;

class MyClass {
    public:
        MyClass operator +();
};

MyClass operator +(const MyClass& a);

If in my main program I call

MyClass a;
MyClass b = +a;

What is called this (internal):

a.operator +()

or this (external) ?:

operator +(a)

The same question for binary operators.

+4
source share
4 answers

A member function is selected: it can be directly associated with the expression a, while a function that is not a member must be converted MyClassto const MyClassbefore binding to the reference parameter. Therefore, calling a member includes a better conversion sequence, which makes it a better overload.

const const , ; , .

+4

, Internal operator.

class MyClass {
public:
    MyClass operator+() {
        std::cout << "Internal operator." << std::endl;
        return *this;
    };
};

MyClass operator+(const MyClass& a) {
    std::cout << "External operator" << std::endl;
    return a;
}

int main() {
    MyClass a, b;
    b = +a;
    return 0;
}
+2

, , : + , - , , . . +, , ( ) .

0

I tested myself a bit:

#include <iostream>
#include "MyClass.h"

using namespace std;

MyClass operator +(const MyClass& a, const MyClass& b)
{ cout << "external" << endl; return a; }

int main() {
    MyClass foo, bar;
    foo + bar;
    return 0;
}

class MyClass {
public:
    MyClass operator+(const MyClass& a) { cout << "internal" << endl; return a; }
};

The output of the program was "internal." My conclusion is that if there is an internal operator that is suitable for the operation, it will be one. I do not see the possibility of making the external, if the internal fits better. But I should note that I just did a little test and did not find out that this is a 100% answer.

0
source

Source: https://habr.com/ru/post/1537189/


All Articles