2011-01-28 21 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

+0

なぜ暗黙の変換に問題がありますか? –

答えて

24

はい、あなたが変換を行うためにoperator type()を定義することができ、そしてそのような変換が必要とされるたびに、はい、それは暗黙的に動作します:

operator int() { 
    return value; 
} 
+0

「明示的に」マークすることはできますか? – KitsuneYMG

+1

@Kitsune:ありがたいことにC++ 0xで。 – GManNickG

+6

おそらく 'const'メソッドでなければなりません。 – MSalters

関連する問題