Friend operator overloading

Can anyone tell me what friend operator overloading
is? I dont understand it. And can you also explain how this code works:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
using namespace std;
class Kasse
{
private:
float fPris;
public:
Kasse(float pris= 0.0);
friend Kasse operator+(Kasse enVare, Kasse enAndenVare);
void udskrivPris();
};

Kasse::Kasse(float pris):fPris(pris)
{
}
Kasse operator+(Kasse enVare, Kasse enAndenVare)
{
/*how does this work on the code longer down?*/
float tmpPris = enVare.fPris+enAndenVare.fPris;
return(Kasse(tmpPris));
}
void Kasse::udskrivPris()
{
cout<<"total pris= "<<fPris<<endl;
}


int main()
{
Kasse enVare(112.50);
Kasse enAndenVare = 46.50;
Kasse enTredieVare = enVare+120.50; 
//how does this works?
Kasse enFjerdeVare = 130.0 + enAndenVare
enTredieVare.udskrivPris();
enFjerdeVare.udskrivPris();
return 0;
}
Last edited on
friend and operator overloading are two distinct terms.

Operator overlaoading allows you to redefine various operators. But it seems you already know that.

Often new function may require access to private parts of the object it manipulates. Declaring the function to be a friend of the class, gives it access to protected and private members of the class without opening up access to anyone else.
Ok but i know that friend operator overloading can take more than 1 arg
How does that work? And then, who is the operands
Last edited on
I think the part you're getting confused with is where to declare it.

You can overload an operator on a class, or you can define an operator that takes a class.

e.g.
1
2
3
4
5
6
class Bottle
{
public:
    bool operator<(const Bottle &) const;
    //...
};


or
1
2
3
4
5
6
7
8
9
10
11
class Bottle
{
friend bool operator<(const Bottle &, const Bottle &);
public:
    //...
};

bool operator<(const Bottle &, const Bottle &)
{
    //...
}

But who are the operands in the friend function?
The left is the object the operation is maked on.
Who is the other 2?
Last edited on
Consider:
1
2
3
Bottle a, b, c;
//...
bool ab = (a < b);


If we used the member operator<, a would be this, the parameter would be b.

If we used the global function, the first parameter would be a and the second parameter would be b.
Ok many thanks kbw!
Topic archived. No new replies allowed.