1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| class MyClass { public: operator int() const { return 42; } operator double() const { return 3.14; } operator bool() const { return true; } };
MyClass obj;
// 情况1:赋值给特定类型的变量(看左值类型) int i = obj; // 需要 int,调用 operator int() double d = obj; // 需要 double,调用 operator double() bool b = obj; // 需要 bool,调用 operator bool()
// 情况2:函数参数(看形参类型) void func(int x) { } void func2(double x) { }
func(obj); // 需要 int,调用 operator int() func2(obj); // 需要 double,调用 operator double()
// 情况3:运算符上下文(看运算符需要什么类型) if (obj) { } // if 需要 bool,调用 operator bool() int result = obj + 10; // + 运算,调用 operator int()
|
具体来说,将该对象转换为什么样的类型由编译器决定。
在类中使用诸如 operator ty() const 的形式可以将对象进行隐式类型转换