3

++,--単項postfix/prefix演算子を完全にオーバーロードして成功し、コードは正常に機能しますが、(++obj)++ステートメントを使用すると予期しない結果が返されます

ここにコードがあります

class ABC
{
 public:
    ABC(int k)
    {
        i = k;
    }


    ABC operator++(int )
    {
        return ABC(i++);
     }

     ABC operator++()
     {
        return ABC(++i);
     }

     int getInt()
     {
      return i;
     }
    private:
   int i;
 };

 int main()
 {
    ABC obj(5);
        cout<< obj.getInt() <<endl; //this will print 5

    obj++;
     cout<< obj.getInt() <<endl; //this will print 6 - success

    ++obj;
    cout<< obj.getInt() <<endl; //this will print 7 - success

    cout<< (++obj)++.getInt() <<endl; //this will print 8 - success

        cout<< obj.getInt() <<endl; //this will print 8 - fail (should print 9)
    return 1;
   }

解決策や理由がありますか?

4

2 に答える 2

7

ABC&一般に、プリインクリメントは、ではなく、を返す必要がありABCます。

これにより、コードのコンパイルに失敗することに注意してください。これは比較的簡単に修正できます(新しい値を作成せずABC、既存の値を編集してから戻ります*this)。

于 2012-10-26T18:49:35.743 に答える
1

プレインクリメントの観点からポストインクリメントを実装するのが最善だと思います。

ABC operator++(int )
{
   ABC result(*this);
   ++*this; // thus post-increment has identical side effects to post-increment
   return result; // but return value from *before* increment
}

ABC& operator++()
{
   ++i; // Or whatever pre-increment should do in your class
   return *this;
}
于 2012-10-26T20:30:55.757 に答える