Hi peeps,
I'm really struggling to get my head around operator overloading.
Please consider the following code:
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
|
class Cents
{
private:
int m_nCents;
public:
Cents(int nCents) { m_nCents = nCents; }
// Add Cents + Cents
friend Cents operator+(const Cents &c1, const Cents &c2);
int GetCents() { return m_nCents; }
};
// note: this function is not a member function!
Cents operator+(const Cents &c1, const Cents &c2)
{
// use the Cents constructor and operator+(int, int)
return Cents(c1.m_nCents + c2.m_nCents);
}
int main()
{
Cents cCents1(6);
Cents cCents2(8);
Cents cCentsSum = cCents1 + cCents2;
std::cout << "I have " << cCentsSum .GetCents() << " cents." << std::endl;
return 0;
}
|
Could you tell me if this is a correct assessment:
In the function starting at line 16, what it's saying is basically:
"people, if an object Cents is declared which tries to add two other Cents objects together, it's ok, just do it"
And in line 26, we try to do just that. So then the compiler says:
"Ok, that was explained to me in the function "Cents operator+(const Cents &c1, const Cents &c2)", so it's ok, replace this Cents object (cCentsSum) with the returned Cents object".
Is it someting like that?
Sorry in advance if i'm talking gibberish!