有没有一种方法可以定义从用户定义类到原始类型(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.
最佳答案
是的,您可以定义一个 operator type()
来进行转换,是的,只要需要这样的转换,它就会隐式地工作:
operator int() {
return value;
}
关于C++ 定义类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4824278/