Why the switch statement cannot be applied on strings?(为什么 switch 语句不能应用于字符串?)
问题描述
编译下面的代码,得到类型非法的错误.
Compiling the following code and got the error of type illegal.
int main()
{
// Compilation error - switch expression of type illegal
switch(std::string("raj"))
{
case"sda":
}
}
您不能在 switch 或 case 中使用字符串.为什么?是否有任何解决方案可以很好地支持类似于打开字符串的逻辑?
You cannot use string in either switch or case. Why? Is there any solution that works nicely to support logic similar to switch on strings?
推荐答案
原因与类型系统有关.C/C++ 并不真正支持字符串作为一种类型.它确实支持常量字符数组的想法,但它并没有真正完全理解字符串的概念.
The reason why has to do with the type system. C/C++ doesn't really support strings as a type. It does support the idea of a constant char array but it doesn't really fully understand the notion of a string.
为了生成 switch 语句的代码,编译器必须理解两个值相等的含义.对于整数和枚举之类的项目,这是一个微不足道的比较.但是编译器应该如何比较 2 个字符串值呢?区分大小写、不敏感、文化意识等......如果不完全了解字符串,则无法准确回答.
In order to generate the code for a switch statement the compiler must understand what it means for two values to be equal. For items like ints and enums, this is a trivial bit comparison. But how should the compiler compare 2 string values? Case sensitive, insensitive, culture aware, etc ... Without a full awareness of a string this cannot be accurately answered.
此外,C/C++ switch 语句通常生成为分支表.为字符串样式开关生成分支表并不容易.
Additionally, C/C++ switch statements are typically generated as branch tables. It's not nearly as easy to generate a branch table for a string style switch.
这篇关于为什么 switch 语句不能应用于字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 switch 语句不能应用于字符串?
基础教程推荐
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- CString 到 char* 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
