c 语言switch中类型,c – 在switch语句中使用类类型:它比使用typeid运算符更好吗?...

我在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的跳转表一样实现

那么,哪种方式更适合在运行时找到对象类型?

编辑:考虑安德烈的评论纠正的问题.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值