1

我是一名大学生,正在从 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 个参数。任何帮助是极大的赞赏!

//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;
}
4

1 回答 1

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;
}
于 2012-10-10T18:34:41.427 回答