2011-01-28 111 views
8

有沒有一種方法來定義從用戶定義的類到基元類型(int,short等)的類型轉換?另外,任何這樣的機制是否需要明確的轉換,還是會隱含起作用?C++定義類型轉換

例如:

// simplified example class 
class MyNumberClass 
{ 
private: 
    int value; 
public: 
    // allows for implicit type casting/promotion from int to MyNumberClass 
    MyNumberClass(const int &ampv) 
    { 
     value = v; 
    } 
}; 
// defined already above 
MyNumberClass t = 5; 

// What's the method definition required to overload this? 
int b = t; // implicit cast, b=5. 
// What's the method definition required to overload this? 
int c = (int) t; // C-style explicit cast, c=5. 
// ... etc. for other cast types such as dynamic_cast, const_cast, etc. 
+1

保持在大多數情況下,隱式轉換是一件壞事。你最好做一個明確的get()函數或其他東西。 – GManNickG 2011-01-28 03:17:35

+0

爲什麼隱式轉換會出現問題? – 2013-02-21 23:27:09

回答

24

是的,你可以定義一個operator type()做轉換,是的,每當需要這樣的轉換,將隱含工作:

operator int() { 
    return value; 
}