【发布时间】:2011-01-28 02:32:44
【问题描述】:
有没有办法定义从用户定义的类到原始类型(int、short 等)的类型转换?此外,任何此类机制都需要显式转换,还是隐式工作?
例如:
// 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()函数或其他东西。 -
为什么隐式转换会有问题?