假设,如果从一种类型的另一种类型的转换是无法通过显式转换e.g 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.
}
显式转换运算符就是返回目标类型的方法。或者我错过了什么? –