C++定义类型转换

hel*_*922 8 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;
    }
};
Run Code Online (Sandbox Code Playgroud)
// 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.
Run Code Online (Sandbox Code Playgroud)

cas*_*nca 24

是的,您可以定义一个operator type()进行转换,是的,只要需要这样的转换,它就会隐式工作:

operator int() {
  return value;
}
Run Code Online (Sandbox Code Playgroud)

  • 可能应该是一个`const`方法. (6认同)