私は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;
}