C ++ Symmetric binary operators with different types

I am learning C ++, and I was wondering if I can get an idea of ​​the preferred way to create binary operators that work with instances of two different types. Here is an example that I did to illustrate my problems:

class A;
class B;

class A
{
    private:
        int x;

    public:
        A(int x);

        int getX() const;

        int operator + (const B& b);
};


class B
{
    private:
        int x;

    public:
        B(int x);

        int getX() const;

        int operator + (const A& A);
};


A::A(int x) : x(x) {}

int A::getX() const { return x; }

// Method 1
int A::operator + (const B& b) { return getX() + b.getX(); }


B::B(int x) : x(x) {}

int B::getX() const { return x; }

// Method 1
int B::operator + (const A& a) { return getX() + a.getX(); }


// Method 2
int operator + (const A& a, const B& b) { return a.getX() + b.getX(); }

int operator + (const B& b, const A& a) { return a.getX() + b.getX(); }


#include <iostream>

using namespace std;

int main()
{
    A a(2);
    B b(2);

    cout << a + b << endl;

    return 0;
};

If I would like to have symmetry between the two types, which method is the best approach in the above code. Are there any possible dangers when choosing one method over another? Does it depend on the type of return? Please explain! Thanks!

+3
source share
4 answers

- ( ) int operator+ (const A& a, const B& b) , . ,

int operator+(const B& b, const A& a) {return a + b;}

.

+8

, + . , ( ).

, + ( ), .

, , .

, ? , .

+3

2 , , . - .

, int int B 1-arg . . "" , .

Uri, : , API, . A a B int? , a b, getX ?

, , A B ints? , , A int B int int(). a + b int , :

#include <iostream>

struct A {
    int x;
    explicit A(int _x) : x(_x) {}
    operator int() {
        return x;
    }
};

struct B {
    int x;
    explicit B(int _x) : x(_x) {}
    operator int() {
        return x;
    }
};

int main() {
    A a(2);
    B b(2);
    std::cout << a + b << "\n";
    std::cout << a - b << "\n";
}
+1

, - . , , . :

matrix operator*( matrix const& a, matrix const& b );
matrix operator+( matrix const& a, matrix const& b ); // and so on

, , (, - ).

:

vector * matrix = vector
matrix * vector_t = vector_t
matrix * matrix = matrix
vector_t * vector = matrix
vector * vector_t = int

(, ):

vector operator*( vector const& v, matrix const& m );
vector operator*( matrix const& m, vector const& v );
matrix operator*( matrix const& m1, matrix const& m2 );
matrix operator*( vector const& v1, vector const& v2 ); // possibly 1x1 matrix, you cannot overload changing only return value

, . , , .

+1
source

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


All Articles