【问题标题】:C++ Defining a type castC++ 定义类型转换
【发布时间】: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 &ampv)
    {
        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() 函数或其他东西。
  • 为什么隐式转换会有问题?

标签: c++ casting


【解决方案1】:

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

operator int() {
  return value;
}

【讨论】:

  • 应该是const方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-23
  • 1970-01-01
相关资源
最近更新 更多