2016-07-28 153 views
8

我試圖理解爲什麼operator int()被調用,而不是定義operator+C++使用,而不是運營商運營商INT()+

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)涉及臨時對象。所以,你必須改變你的operator+簽字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"; 
} 

它打印帶:

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

operator int而找到正確的過載打印出來給cout被調用。