Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/131.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Can';t重载=使object1=0; 我是一名大学生,正在从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;_C++_Operator Overloading - Fatal编程技术网

Can';t重载=使object1=0; 我是一名大学生,正在从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;

Can';t重载=使object1=0; 我是一名大学生,正在从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;,c++,operator-overloading,C++,Operator Overloading,我从论坛上了解到,我不能使=一个朋友过载,这使我可以为函数接受2个参数。非常感谢您的帮助 //code for my << overload ostream& operator << (ostream& output, const Weight& w) { switch(w.pounds) { case 1: case -1: output << w.pounds << "lb";

我从论坛上了解到,我不能使=一个朋友过载,这使我可以为函数接受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;
}
//我的
这是错误的,您正在返回对临时对象的引用。此对象超出范围,然后您得到的结果不正确

通常,
operator=
是赋值,这意味着您希望更改对象本身的状态。因此,它通常应如下所示:

//Weight.cpp
Weight& Weight::operator=(const int number)
{
   // whatever functionality it means to assign the number to this object
   return *this;
}
这是错误的,您正在返回对临时对象的引用。此对象超出范围,然后您得到的结果不正确

通常,
operator=
是赋值,这意味着您希望更改对象本身的状态。因此,它通常应如下所示:

//Weight.cpp
Weight& Weight::operator=(const int number)
{
   // whatever functionality it means to assign the number to this object
   return *this;
}

我们可以看到
运算符的重载吗编译没有问题,但这是我的w5=0打印输出对不起,我看错了问题。它看起来像是您的
…而实际上您并没有将
编号
存储在赋值运算符中的任何位置,只是创建了一个要返回的对象。通常是存储
编号
,然后返回
*此
。我们可以看到
运算符的重载吗编译没有问题,但这是我的w5=0打印输出对不起,我读错了问题。它看起来像是您的
…而实际上您并没有将
编号
存储在赋值运算符中的任何位置,只是创建了一个要返回的对象。通常是存储
编号
,然后返回
*此
.Killer。我知道我要拿回地址,但我想我的头撞在墙上太久了,我看不见了。这很有效。非常感谢!杀手。我知道我要拿回地址,但我想我的头撞在墙上太久了,我看不见了。这很有效。非常感谢!
//Weight.cpp
Weight& Weight::operator=(const int number)
{
   // whatever functionality it means to assign the number to this object
   return *this;
}