2016-03-23 13 views
4

私のオーバーロードされた++(プレバージョン)が値を更新していない理由を説明できますか?あなたのオーバーロード演算子のsignatureがあるべきオーバーロードされた++演算子がC++で動作していません

circle circle:: operator++() 
{ 
    Area = Area * 2.0; 
    return *this; 
} 
///////////////////////////// 

int main() 
{ 
    class circle c1(4, 1, -1), c2(12, 4, 6); 
    c1.output(); 
    c1++; 
    c1.output(); 

    system("pause"); 
    return 0; 
} 
+4

postfixバージョン 'c1 ++'はあなたが呼び出していませんか? – EdChum

+1

また、あなたのバージョンが – EdChum

+0

と一致していないので、あなたの[署名](http://en.cppreference.com/w/cpp/language/operator_incdec)をチェックする必要があります。ポストインクリメント 'c1 ++'の署名では、円と円::演算子++(int) 'あなたの現在の演算子++()は、プリインクリメント '++ c1'のために動作します。 – Vishal

答えて

5

:スニペットは、このようなものです

circle& operator++(); // return by reference and this is prefix. 

しかし、それはする必要がありますので、あなたは、接尾辞を使用します。

circle operator++ (int); // int is unused 

署名を変更していますで十分ではありません。プレフィックスロジックを実装し、初期値を保存せずに値を直接変更するからです。だから、(c++).output()のような結合された式であなたの実装にpostfix演算子を使用すると、期待される意味を尊重することはできません。ここで

バージョンの両方のimplemetnation:

circle& operator++() { // prefix 
    Area = Area * 2.0; // you can change directly the value 
    cout << "prefix"<<endl; 
    return *this;  // and return the object which contains new value 
} 

circle operator++ (int) { // postfix 
    circle c(*this);  // you must save current state 
    Area = Area * 2.0; // then you update the object 
    cout << "postfix"<<endl; 
    return c;   // then you have to return the value before the operation 
} 

そして、ここで両者の差を表示するonline demo

+1

が返されますが、結果は変わりません。 OPは式を直接使用していません。このエラーはコメントで強調表示されています。 – juanchopanza

+0

円と演算子++()はありません。クラスまたは列挙型のパラメータが必要ですか? –

+0

@TaimurAhmedはい、実際には後置インクリメント用です。私はあなたが入力している間に私の答えを完了していた。 – Christophe

7

これは、プレフィックスに過負荷がかかっていて、それが後置式を呼び出すためです。 ++c1;に電話する必要があります。あなたにも接尾辞をオーバーロードする必要がc1++;使用するには:

circle operator++ (int); 
+0

あなたの回答を更新して、他の可能性のある修正について言えますか? OPは 'c1 ++; 'を呼び出すことを意味するかもしれません – quamrana

+0

はい、私はそれを行うべきです。ありがとう – DimChtz

0

ここでは、バージョンプレフィックスとポストフィックスの両方があります。 c1 ++(1)のような呼び出しの場合には、いくつかのコードを追加できます。(もちろん必要ならば)

circle circle:: operator++() // prefix version 
{ 
    Area = Area * 2.0; 
    return *this; 
} 

circle& circle::operator++(int n) { //postfix version 
    if(n != 0)    // Handle case where an argument is passed. 
     //some code 
    else 
     Area = Area * 2.0;  // Handle case where no argument is passed. 
    return *this; 
} 


int main() 
{ 
    class circle c1(4, 1, -1), c2(12, 4, 6); 
    c1.output(); 
    c1++; 
    ++c1; 
    c1.output(); 

    system("pause"); 
    return 0; 
} 
関連する問題