c++ - 在类中声明一个 "list"的常量

标签 c++ class constants c++03

我想在我的类中创建一个常量列表,但我不知道如何正确地做到这一点。

首先我尝试将它放在这样的枚举中:

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";

Here is a live example.

关于c++ - 在类中声明一个 "list"的常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54089172/

相关文章:

c++ - 使用结构成员创建映射会抛出 bad_alloc

python - (Python 2.7)使用访问器/更改器(mutator)从类访问变量

java - 如何使用定时器类

java - 涉及魔数(Magic Number)的全局常量的最佳实践

c++ - 我应该在没有有意义的恢复的情况下捕获异常吗?

c++ - 在 C++ 中通过 libxml2 解析部分 XML 时过滤掉 namespace 错误

c++ - 全局外部人员。字符串和字符之间的区别*

php - 如何确保 CONSTANTS 始终被设置

c++ - 在 Nvidia NPP ImageCPU 对象中设置像素值?

c++ - 迭代器成员行为