ユーザー定義クラスからプリミティブ型(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 &v)
{
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.
キープ暗黙的な変換は、ほとんどの場合、悪いことです。あなたは明示的な 'get()'関数などを作る方が良いでしょう。 – GManNickG
なぜ暗黙の変換に問題がありますか? –