I am a college student making the switch from java to c++ . We have been introduced to overloading operators which I get for the most part, but for my assignment I have been stumped. The main asks for:
Weight w1( -5, 35 ), w2( 5, -35 ), w3( 2, 5 ), w4( 1 ), w5, w6;
//later on in main
cout << "(w5 = 0) is " << ( w5 = 0 ) << endl;
My weight objects hold two ints, one for pounds one for ounces. When my program gets to this line w5 is already set to (0,0) however I feel like I’m returning the address as I get a massively long number when I print w5. Here is the code I have in .h and .cpp for the specific overload of =
//Weight.h
Weight& operator=(const int);
//Weight.cpp
Weight& Weight::operator=(const int number)
{
Weight changer(number); //constructs weight object with one int to (int, 0)
return changer;
}
I have learned from forums that I can’t make = a friend overload which has allowed me to take in 2 args for the function. Any help is greatly appreciated!
//code for my << overload
ostream& operator << (ostream& output, const Weight& w)
{
switch(w.pounds)
{
case 1:
case -1:
output << w.pounds << "lb";
break;
case 0:
break;
default:
output << w.pounds << "lbs";
break;
}
switch(w.ounces)
{
case 1:
case -1:
output << w.ounces << "oz";
break;
case 0:
break;
default:
output << w.ounces << "ozs";
break;
}
if (w.pounds == 0 && w.ounces == 0)
{
output << w.ounces << "oz";
}
return output;
}
This is wrong, you are returning a reference to a temporary object. This object goes out of scope, and then you have your incorrect results.
Generally,
operator=is assignment, meaning you want to change the state of the object itself. It should therefore generally look like this: