# How can I implement a friendly function to subtract two numbers m1 and m2?

1

The function that adds them is given by: In the file that contains the int main ():

`````` add(m1,m2, sum);
cout << "The sum is:";
sum.display_money();
``````

In the .h file:

`````` friend void add(AltMoney m1, AltMoney m2, AltMoney& sum);
``````

In the .cpp file

``````void add(AltMoney m1, AltMoney m2, AltMoney& sum)
{
int extra = 0;
sum.cents = m1.cents + m2.cents;
if(sum.cents >=100){
sum.cents = sum.cents - 100;
extra = 1;
}

sum.dollars = m1.dollars + m2.dollars + extra;
}
``````

From that implementation I want to subtract one from the other ...

The sum I am calling by reference, but I can not find the logic to subtract.

Thanks for your time and help.

asked by Gabriel Valedon 12.02.2017 в 18:05
source

2

Friendly functions allow access to private data objects as if this function had the permissions of member functions; without declaring the function as a friend, the usual restrictions apply, for example:

``````class C
{
int i;
};

void Suma_1(C &c)
{
++c.i; // Error, 'C::i' es privado!
}

int main()
{
C c;
Suma_1(c);
return 0;
}
``````

For a function to be considered a friend, you must declare yourself inside the object that you want to grant access to; in this way the friendly function will obtain the same access levels as the members of that object:

``````class C
{
// Declaramos la funcion 'Suma_1' como amiga de la clase 'C'.
friend void Suma_1(C &);
int i;
};

void Suma_1(C &c) // Definimos la funcio 'Suma_1'.
{
++c.i; // Correcto, 'C::i' es privado, pero 'Suma_1' es amiga.
}
``````