My understanding of friend functions

Sometimes a non-member function may need access to private members, which it accepts as a tool. A function friendis a non-member function that provides private access to the classes it is friends with.

Class X{
    int number;
public:
    X& operator+=(const X& rhs);//a += b is a.operator(b)
    friend int& operator+=(int& addthis, const X& rhs);//add this += b is I don't know what lol
}
X& operator+=(const X& rhs){
    this->number = this->number + rhs.number;        
}
int& operator+=(int& addthis, const X& rhs){
     addthis = addthis + rhs.number;
     return *this;
}

I read that if I wanted to do +=for an object object += int, just reload the operator +=, but what if it intappeared in front of the object. Tell int += objectme Than I would have to write it as a function friend, and where I get a little lost. Why can't I write int& operator+=(int& addthis, const X& hrs);as a member function? I believe that a function friendcan work with other classes, since it is a non-member function, so it is not assigned to any particular class?

, , friend, -. , .

+4
5

, - - x += y, x y +=.

x += y x.operator+=(y), , x y , +=.

2 += y ( , , -)

2 += y 2.operator+=(y), . , 2 ; ( ), .

2 += y operator+=(2, y), .

+1

operator+= int X:

struct X{
    int number;
    operator int() const
    {
        return number;
    }
    //...
}

, , friend -approach, . , , , , operator-=, operator*= ..

+2

, operator*, operator+ operator+= operator@, @ - , -, . .

. ++. - - , , , . . , ( + ?). , , , .

+2

, int += X , , - lhs, rhs. int , , -.

, :

class X;

int operator+=(int addthis, const X& rhs);

class X{
    int number;
public:
    X& operator+=(const X& rhs);//a += b is a.operator(b)
    friend int operator+=(int addthis, const X& rhs);//add this += b is I don't know what lol
};

X& X::operator+=(const X& rhs){
    this->number = this->number + rhs.number; 
    return *this;
}
int operator+=(int addthis, const X& rhs){
     addthis = addthis + rhs.number;
     return addthis;
}
  • int
  • class class
  • return

, X += int -, int += X , friend X.

int += X , , :

X x;
int i = 2;
i += x;
+1
source

The modifier is friendintended only for displaying data private. As a rule, you do not define a function friendas a non-member if it depends only on the private data of the class, which can be defined as a member function for.

A better example might be ostream::operator<<or istream::operator>>.

0
source

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


All Articles