C ++定义类型转换

时间:2011-01-28 02:32:45

标签: c++ casting

有没有办法定义从用户定义的类到基本类型(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.

1 个答案:

答案 0 :(得分:24)

是的,您可以定义operator type()进行转换,是的,无论何时需要进行此类转换,它都会隐式工作:

operator int() {
  return value;
}