【发布时间】:2019-04-04 02:06:38
【问题描述】:
这样做更好吗:
class Foo{
std:string option1(MY_ENUM type){
static const std:string f1 = "a";
static const std:string f2 = "b";
static const std:string f3 = "c";
// ...
switch (type) {
case (TYPE_1):{
return f1;
break;
}
case (TYPE_2):{
return f2;
break;
}
// ...
}
}
或者这样做:
class Foo {
private:
const std:string f1 = "a";
const std:string f2 = "b";
const std:string f3 = "c";
public:
std:string option1(MY_ENUM type){
// ...
switch (type){
case (TYPE_1):{
return f1;
break;
}
case (TYPE_2):{
return f2;
break;
}
// ...
}
}
同样,我会做类似的事情来将枚举转换为字符串。 将字符串保留为函数中的静态常量还是类中的私有字符串更好? - 除了我,没有人会编辑课程。 - 类中的任何其他函数是否知道字符串的值是什么并不重要,因为它是 const 他们无论如何都不能修改它。
在运行时和编译期间哪个更便宜并且开销更少?哪种做法更好?
【问题讨论】:
-
只需创建一个包含对 { enumValue, stringValue } 的表。
-
在
return之后不需要break。这使得switch版本可能是你能得到的最简单的版本。 -
您确定不能使用
const char*'s 而不是正确的std::strings?