C++ primer 类类型转换问题
考虑 manip 函数,它接受一个 SmallInt 类型的实参:
void manip(const SmallInt &);
double d;
manip(d); // ok: use SmallInt(double) to convert the argument
class SmallInt {
public:
// conversions to SmallInt from int and double
SmallInt(int = 0);
SmallInt(double);
// Conversions to int or double from SmallInt
// Usually it is unwise to define conversions to multiple
arithmetic types
operator int() const { return val; }
operator double() const { return val; }
// ...
private:
std::size_t val;
};
我知道SmallInt可以转换为double 类型, 但d可以转换为SmallInt 类型,过程是怎样的? 类类型转换 都是双向的吗?
[解决办法]
不是什么双向的问题。SmallInt可以转换为double 类型是因为在类SmallInt里面有一个转换符,operator double() const { return val; }
d可以转换为SmallInt 类型是因为有一个构造函数:SmallInt(double);