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;

私のウェイトオブジェクトは2つのintを保持し、1つはポンド用、もう1つはオンス用です。プログラムがこの行に到達すると、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 に答える