我遇到了这个问题: Why switch statement cannot be applied on strings? 并想知道答案是否:
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.
仍然适用,即使在 C++11/14 中使用 std:string
。是否有多个 else if(...)
的替代方案?
最佳答案
是的,它仍然成立。
如前所述here ,条件可以是:
any expression of integral or enumeration type, or of a class type contextually implicitly convertible to an integral or enumeration type, or a declaration of a single non-array variable of such type with a brace-or-equals initializer.
我遇到了 that question几天前,我猜你可以从那里找出 if/else
链的替代解决方案。
如果可能的话,这主要取决于您的实际问题,无论如何,基本思想是使用可调用对象的映射,从中使用您的对象(在本例中为字符串)作为键进行访问。当然,在使用之前必须以某种方式填充该 map 。
关于c++ - "Why switch statement cannot be applied on strings?"的答案是否仍然正确,即使使用 C++11/14?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35386918/