我是一名大学生,正在从java转换为c ++。我们已经介绍过我在大多数情况下都会重载运算符,但对于我的任务,我一直很难过。主要要求:
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;
我的体重对象有两个整数,一个是一磅,一盎司。当我的程序到达这一行时,w5已经设置为(0,0)但是当我打印w5时,我觉得我正在返回地址,因为我得到了一个很长的数字。这是我在.h和.cpp中的代码,用于=
的特定重载//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;
}
我从论坛中了解到,我无法做出=朋友超载,这让我可以接受2个args的功能。非常感谢任何帮助!
//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;
}
答案 0 :(得分:4)
//Weight.cpp
Weight& Weight::operator=(const int number)
{
Weight changer(number); //constructs weight object with one int to (int, 0)
return changer;
}
这是错误的,您将返回对临时对象的引用。此对象超出范围,然后您的结果不正确。
通常,operator=
是赋值,这意味着您要更改对象本身的状态。因此,它通常应如下所示:
//Weight.cpp
Weight& Weight::operator=(const int number)
{
// whatever functionality it means to assign the number to this object
return *this;
}