【发布时间】:2011-11-07 06:37:18
【问题描述】:
假设,如果无法通过显式转换(例如static_cast)从一种类型转换另一种类型,是否可以为其定义显式转换运算符?
编辑:
我正在寻找一种方法来为以下内容定义显式转换运算符:
class SmallInt {
public:
// The Default Constructor
SmallInt(int i = 0): val(i) {
if (i < 0 || i > 255)
throw std::out_of_range("Bad SmallInt initializer");
}
// Conversion Operator
operator int() const {
return val;
}
private:
std::size_t val;
};
int main()
{
SmallInt si(100);
int i = si; // here, I want an explicit conversion.
}
【问题讨论】:
-
显式转换运算符将是返回目标类型的方法。还是我错过了什么?
标签: c++ type-conversion explicit