假设,如果通过显式转换无法从一种类型转换另一种类型,例如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.
}