我经常需要定义与类关联的字符串常量。例如 XML 属性、默认文件名等等。
在Java中我会简单地定义类似的东西
public static final String KEY = "attribute";
在类或接口内部。
在 C++ 中,以下内容将无法编译:
class Example {
public:
static const std::string KEY = "attribute";
}
相反,我必须写:
class Example {
public:
static const std::string KEY;
}
const std::string Example::KEY = "attribute";
这是我绝对想避免的,因为它的冗余和冗长。
到目前为止我发现的最好的解决方案是使用函数:
class Example {
public:
static std::string KEY() const { return "attribute"; }
}
这也提供了一些封装性和灵活性。然而,仅仅使用函数来定义常量似乎有点奇怪。
所以我的问题是,这个解决方案是否有主要缺点?如果有,有哪些更好的替代方案?
在 c++03 中,最好的选择是按照您正在使用的方式使用函数,但这很尴尬。唯一的问题是,你为什么要回来std::string
并支付建筑费用,当你可以返回时const char* const
免费。
如果由于某种原因你真的必须const std::string
(同样,它违背了我的整个经验,所以你可能需要重新考虑)以下代码在效率方面效果最好(你当前的版本调用std::string
每次调用的构造函数!):
class Example {
public:
static const std::string& key() {
static const std::string the_key = "That's my key!";
return the_key;
}
}
在 c++11 中,您有多种选择,我发现其中最好的一个constexpr
:
class Example {
public:
static constexpr const char* const KEY = "TheKey";
}
另一个选项是就地初始化 const 字符串,但为什么要为此付出代价呢?
class Example {
public:
static const std::string KEY = "TheKey";
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)