Dado & operator+(Dado const & d){
int dado2; set(dado2);
d.get()+dado2.get();
return *this;
}
This operator will not fulfill its function for three reasons:
- They ask you to return the result in an integer and you are returning a die
- The operator
+
should not modify the state of either of the two dice. For this is the operator +=
- The operator, as declared, is not a member function of
Dado
, so you'll have to pass the two dice.
The first two points I think you understand quite well, if they ask you for an integer and you return an object of type Dado
, the interface of the function is not correct and about modifying objects, I think it is also clear.
Some operators in C ++ can (or can not) be members of a class. The basic differences are the following:
- If implemented as a member function, you can save a parameter.
- If implemented as a member function you can access the protected and private parts.
- If implemented as a free function, you gain freedom and reduce the coupling.
- There are cases in which the operator can not be implemented as a member function.
A practical example:
struct POO
{
int offset;
// Operador miembro
int operator+(int n) const
{ return offset + n; }
};
// Función libre, nota que tiene 2 parámetros
int operator-(POO p, int n)
{ return p.offset - n; }
// Función libre
// No se podría implementar como función miembro
int operator+(int n, POO p)
{ std::cout << "operador libre: " << n + p.offset << '\n'; }
int main()
{
POO p;
p.offset = 10;
std::cout << p + 5 << '\n'; // imprime "15"
std::cout << p - 5 << '\n'; // imprime "5"
std::cout << 5 + p << '\n'; // imprime "operador libre: 15"
}
So your + operator overload could implement it in two different ways:
Member feature
class Dado{
public:
int operator+(Dado const& d2) const;
};
int Dado::operator+(Dado const& d2) const{
return _valor + d2._valor;
}
Note that the function ends in const
, this tag forces the compiler to show an error at compile time if you try to modify the state of the object, for example by doing this->_valor = 10;
.
Free function
int operator+(Dado const& d1, Dado const& d2)
{
return d1.getValor() + d2.getValor();
}
In this case the function can not be const
since it does not belong to any class (because it is a free function). However, both parameters are const
, so you will not be able to modify them.
The result in both cases is the same, you can choose the one you like the most.