2012-04-22 159 views
1

我有一類名爲幣作爲ostream的操作符重載

class Dollars 
    { 
    private: 
      int dollars; 
    public: 
    Dollars(){} 
    Dollars(int doll) 
    { 
      cout<<"in dollars cstr with one arg as int\n"; 
      dollars = doll; 
    } 
    Dollars(Cents c) 
    { 
      cout<<"Inside the constructor\n"; 
      dollars = c.getCents()/100; 
    } 
    int getDollars() 
    { 
      return dollars; 
    } 
    operator int() 
    { 
      cout<<"Here\n"; 
      return (dollars*100); 
    } 

    friend ostream& operator << (ostream& out, Dollars& dollar) 
    { 
      out<<"output from ostream in dollar is:"<<dollar.dollars<<endl; 
      return out; 
    } 
    }; 

    void printDollars(Dollars dollar) 
    { 
      cout<<"The value in dollars is "<< dollar<<endl; 
    } 

    int main() 
    { 
      Dollars d(2); 
      printDollars(d); 
      return 0; 
    } 

在上面的代碼,如果我刪除重載ostream的操作,然後它去

operator int() 
    { 
      cout<<"Here\n"; 
      return (dollars*100); 
    } 

但在提供ostream的超載不去那裏。

我的困惑

Why isn't there any return type for operator int() function as far as my understanding says that all functions in C++ should have a return type or a void except the constructors.

不是int的,我可以提供定義的數據類型有一些用戶?

在什麼情況下我應該使用這個功能?

回答

3

這種類型的運算符稱爲conversion function。在你的情況下,它從Dollars轉換爲int。該語法是標準的,你不能指定返回類型(你已經聲明瞭類型)。

如果需要,您可以爲自定義類型創建轉換運算符。你可以有:

operator Yen() { ... } 
operator Euro() { ... } 

隨後的Dollar一個實例可以隱式使用這些函數轉換爲YenEuro,而無需投(或構造在YenEuro班採取Dollar)。從 「C++ 03」 標準

實施例(§12.3.2/ 2):

class X { 
// ... 
public: 
operator int(); 
}; 

void f(X a) 
{ 
int i = int(a); 
i = (int)a; 
i = a; 
} 

C++ 11允許轉換功能被標記爲明確。在這種情況下,轉換功能僅在直接初始化期間考慮。 (這是一般的一件好事做,以避免意外的轉換,特別是對基本類型。)該示例中對於該標準(§12.3.2/ 2):

class Y { }; 
struct Z { 
explicit operator Y() const; 
}; 

void h(Z z) { 
Y y1(z);  // OK: direct-initialization 
Y y2 = z; // ill-formed: copy-initialization 
Y y3 = (Y)z; // OK: cast notation 
} 

(和C++ 11個狀態表示轉換函數不能聲明static。)

+3

注意:C++ 11允許將'explicit'限定符應用於轉換運算符。我會推薦它。 – 2012-04-22 13:30:15

+0

+1 @ @ MatthieuM。的建議,如果我使用C++ 03,我很可能會提供特殊的功能,而不是讓自己處於隱藏的轉換過程中。 – 2012-04-22 13:35:26

+0

謝謝@MatthieuM。,增加了一些關於這方面的信息。 – Mat 2012-04-22 13:42:58