Friend vs member function in C ++ operator overload

I used to learn about operator overloading in C ++ as member functions, as well as functions of a friend of a class. Although, I know how to overload operators in C ++ using both methods. But I'm still confused that ** which is better? Member function or friend function to overload operators, which should I use and why? Please guide me! Your answer will be greatly appreciated. I will be glad and grateful for your answers.

+6
source share
4 answers

The choice is not "member or friend", but "member or non-member."
(Friendship is often abused and is usually taught too early in schools.)

, -, .

:

class A
{
public:
    explicit A(int y) : x(y) {}
    A plus(const A& y) const { return A{x + y.x}; }
private:
    int x;
};

A operator+(const A& lhs, const A& rhs) { return lhs.plus(rhs); }

: , , ( , ' ).

:

// Can't be a member because the int is on the left.
A operator+ (int x, const A& a) { return A{x} + a; }

, (, + +=), mutating , -:

class B
{
public:
    explicit B(int y) : x(y) {}
    B& operator+= (const B& y) { x += y.x; return *this; }
private:
    int x;
};

B operator+(B lhs, const B& rhs) { return lhs += rhs; }

:

class C
{
public:
    explicit C(int y) : x(y) {}
    C& add(const C& y) { x += y.x; return *this; }
private:
    int x;
};

C& operator+=(C& lhs, const C& rhs) { return lhs.add(rhs); }
C operator+(C lhs, const C& rhs) { return lhs += rhs; }
+3

- , . , , , .

struct A
{
    A operator+=(A const & second); 
};

A operator+(A const &first, A const &second)
{
    A temp(first);
    temp += second;
    return temp;
}

one, , , : (friend ), , . : A a int A ( , a int), -, .

A a1, a2; 
a1 + a2; // OK 
a1 + 42; // OK
42 + a2; // KO

.

A a1, a2; 
a1 + a2; // Ok 
a1 + 42; // Ok 
42 + a2; // Ok

++, , std::string.

#include <iostream>
#include <string>

int main()
{
    std::string s {"World"};
    // Works with absolutely no problem.
    std::string chaine = "Hello " + s;
    std::cout << chaine << std::endl;
}

, SO, .

+2

, .

, , -. : :

class A {
    ...
    A operator + (const class A& other);   // naturally a member function
    ...
};

, , , , friend

std::outstream& operator << (std::outstream& out, const class A& a);

class A {
    ...
    friend std::outstream& operator << (std::outstream& out, const class A& a); // must be friend here
};

std::outstream, A , std::outstream ++...

+1

, , : , - . , , , .

( ).

, . - , (, < < i/o).

0

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


All Articles