我在c标准$6.4.2中看到了关于switch语句的下面的事情.
Switch语句可以采取一个条件.
The condition shall be of integral type, enumeration type, or of a class type for which a single conversion function to
integral or enumeration type exists (12.3). If the condition is of class type, the condition is converted by calling that
conversion function, and the result of the conversion is used in place of the original condition for the remainder of this
section
我尝试下面的代码,工作正常.
class Test
{
public:
operator int() { return 1; }
};
int main()
{
Test obj;
switch(obj)
{
case 1: cout<
break;
}
}
与使用typeid运算符查找对象类型相比,这是一种更好的方法吗?
在switch case方式中,开销是每个类应该有一个唯一的整数id,它将由转换函数返回.
以typeid方式,如果我们使用类似typeid(obj)== typeid(Test),如果我们有很多类类型,if else链将会很长.代码可读性降低.与switch情况相比可能更慢,因为switch case可能像Compiler的跳转表一样实现
那么,哪种方式更适合在运行时找到对象类型?
编辑:考虑安德烈的评论纠正的问题.