2016-07-28 9 views
8

の私はoperator int()が呼び出さ代わりに定義されたoperator+C++()の代わりに演算子+

class D { 
    public: 
     int x; 
     D(){cout<<"default D\n";} 
     D(int i){ cout<<"int Ctor D\n";x=i;} 
     D operator+(D& ot){ cout<<"OP+\n"; return D(x+ot.x);} 
     operator int(){cout<<"operator int\n";return x;} 
     ~D(){cout<<"D Dtor "<<x<<"\n";} 
}; 

void main() 
{ 
    cout<<D(1)+D(2)<<"\n"; 
    system("pause"); 
} 

私の出力がされた理由を理解しようとしています:

int Ctor D 
int Ctor D 
operator int 
operator int 
3 
D Dtor 2 
D Dtor 1 
+0

あなたの*質問*は何ですか? – MikeCAT

+2

@MikeCATこれは最初の行です。不明な点は何ですか? – Rotem

+3

'operator int()'を削除すると、その理由がわかるでしょう。少なくとも、ほとんどのコンパイラとそのデフォルトオプションを使ってください。 – chris

答えて

9

あなたの表現D(1)+D(2)が含ま一時的なオブジェクト。だから、あなたはそれが印刷さconst-ref

#include <iostream> 
using namespace std; 

class D { 
    public: 
     int x; 
     D(){cout<<"default D\n";} 
     D(int i){ cout<<"int Ctor D\n";x=i;} 
     // Take by const - reference 
     D operator+(const D& ot){ cout<<"OP+\n"; return D(x+ot.x);} 
     operator int(){cout<<"operator int\n";return x;} 
     ~D(){cout<<"D Dtor "<<x<<"\n";} 
}; 

int main() 
{ 
    cout<<D(1)+D(2)<<"\n"; 
} 

で取ることoperator+のあなたの署名を変更する必要があります。coutにそれを印刷するための正しい過負荷を見つけながら

 
int Ctor D 
int Ctor D 
OP+ 
int Ctor D 
operator int 
3 
D Dtor 3 
D Dtor 2 
D Dtor 1 

operator int呼び出されます。

関連する問題