语法是switch ( condition ) statement with
条件 - 整数或枚举类型的任何表达式,或 contextually 隐式 可转换为整数或枚举类型的类类型,或单个非这种类型的数组变量,带有大括号或等号初始值设定项。
取自cppreference.
这意味着您只能对整数或枚举类型进行切换。为了使编译器能够将 Wrapper 隐式转换为整数/枚举类型,您需要删除显式关键字:
显式说明符指定构造函数或转换函数(C++11 起)不允许隐式转换
您也可以将 Wrapper 转换为 int 类型。
编辑地址@acraig5075 评论:
您必须注意哪个运算符是显式的,哪个是隐式的。如果两者都是隐式的,则代码将无法编译,因为会有歧义:
struct Wrapper
{
operator int() { return 0; }
operator bool() { return true; }
};
source_file.cpp:在函数“int main()”中:source_file.cpp:12:14:
错误:'Wrapper' 的默认类型转换不明确
开关 (w) {
^ source_file.cpp:12:14: 注意:候选转换
包括‘Wrapper::operator int()’和‘Wrapper::operator bool()’
消除歧义的唯一方法是进行强制转换。
如果只有一个运算符是显式的,则另一个运算符将被选择用于 switch 语句:
#include <iostream>
struct Wrapper
{
explicit operator int() { return 0; }
operator bool() { return true; }
};
int main()
{
Wrapper w;
if (w) { /** this line compiles **/std::cout << " if is true " << std::endl; }
switch (w) {
case 0:
std::cout << "case 0" << std::endl;
break;
case 1:
std::cout << "case 1" << std::endl;
break;
}
return 0;
}
输出:
if is true
case 1
w 已隐式转换为 1 (true)(因为 operator int 是显式的)并执行 case 1。
另一方面:
struct Wrapper
{
operator int() { return 0; }
explicit operator bool() { return true; }
};
输出:
if is true
case 0
w 已隐式转换为 0,因为运算符 bool 是显式的。
在这两种情况下,if 语句都是正确的,因为 w 在 if 语句中被评估为 上下文 为布尔值。