我想在我的类中创建一个常量列表,但我不知道如何正确地做到这一点。
首先我尝试将它放在这样的枚举中:
class CMyClass{
public:
enum EKeyword
{
E_PARAM1 = "myString1",
E_PARAM2 = "myString2",
...
};
但似乎不可能(-> error C2057: expected constant expression)
我知道我可以用#define 或使用“static const ...”声明一个一个地声明我的每个常量,但我喜欢使用:EKeyword.E_PARAM1 来获取我的字符串,但我不喜欢想要将这些常量设置为全局。
有什么建议吗?
最佳答案
您不能在 C++ 中使用字符串表示形式创建 enum
。您将需要一个字符串列表。如果您不想强制在结构(如 enum class
)中引用它们,请将它们添加到结构中:
class CMyClass {
public:
struct EKeyword {
static constexpr char const* PARAM_1 = "myString1";
...
private:
EKeyword(); // Disables the ability to construct an EKeyword struct.
};
...
然后在类中使用如下:
EKeyword::PARAM_1
课外将是:
CMyClass::EKeyword::PARAM_1
如果您仅限于 c++03
,您将需要在 cpp 文件中创建字符串值:
// .hpp
class CMyClass {
...
struct EKeyword {
static char const* PARAM_1;
...
// .cpp
char const* CMyClass::EKeyword::PARAM_1 = "myString1";
关于c++ - 在类中声明一个 "list"的常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54089172/