I have a class named ThreeDigits on c++ code. I overloaded the + operand, this way:
ThreeDigits* ThreeDigits::operator+(const ThreeDigits &number) const
{
double result= getNumber()+number.getNumber();
ThreeDigits* new_result=new ThreeDigits(result);
return new_result;
}
but when I write on the main function:
ThreeDigits* first=new ThreeDigits(2.55998);
ThreeDigits* second=new ThreeDigits(5.666542);
ThreeDigits* result=first+second;
I get the following compilation error:
invalid operands of types ThreeDigits* and ThreeDigits* to binary operator+
Can you tell me what is the problem? thanks
You are trying to sum pointers to objects instead of the objects themselves. To invoke the overloaded operator you must call it on objects, thus dereferencing the pointers.
By the way, creating all those objects with
newa terrible way to do C++; in C++, unlike Java/C#, you should usenewonly when you have to, and allocate all the rest on the stack. Having theoperator+return a pointer to a newly created object is an abomination.The C++ way of writing your code would be:
By the way, the usual way of overloading arithmetic operators is first overloading the assigning versions (+=, -=, …) and then build the “normal” version over them. For more info about operator overloading see the operator overloading FAQ.