#include <iostream> using namespace std; class SmallInt { public: /** * implicit constructor * 实现int类型转换为SamllInt类型 */ SmallInt(const int val): value(val) { cout << "SmallInt(const int val)" << endl; } /** * class-type conversion * 无显式返回类型 * 无形参 * 必须定义成类的成员函数 * 一般被定义成const类型 */ operator int()const /* SmallInt类型在需要的时候会转化为int类型 */ { cout << "operator int()const" << endl; return value; } int getValue() const { return value; } private: int value; }; void testTypeConversion() { SmallInt smallInt = 1;/* SmallInt smallInt = SmallInt(1) */ cout << smallInt.getValue() << endl; cout << smallInt + 2 << endl; } void testTypeConversion2nd() { SmallInt smallInt = 3.14;/* 3.14转化为int型为3 */ cout << smallInt.getValue() << endl; cout << smallInt + 3.14 << endl; /* SmallInt类型先转化为int,再转化为double*/ } int main() { testTypeConversion(); testTypeConversion2nd(); return 0; } |
运行结果如下图所示: