如何使用C ++中的某个语句初始化类const static结构

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何使用C ++中的某个语句初始化类const static结构相关的知识,希望对你有一定的参考价值。

有一个const static std :: map属于一个类。是否有一种形式可以形成以下代码:

// file A.h
class A {
   public:
           const static std::map<std::string, int> m_name2code;
   public:
           static int getCode(std::string name);
   private:
           const static char *name[3];
}

// file A.cpp
const char * A::name = {
            "hello", "the", "world" }
for (int index = 0; index < 3; ++index) {
        m_name2code.insert(std::string(name[i]), i+1);
}

作为上面的代码,我想知道是否有一些语法使用control-statement来初始化class-const-static成员?

非常感谢你...

答案

您将初始化分为两个阶段:

  1. 在函数中构建映射并返回结果。
  2. 从函数的结果初始化static变量。

例如:

namespace {
    std::map<std::string, int> build_map() {
        std::map<std::string, int> rc;
        const char * A::name = { "hello", "the", "world" };
        for (int index = 0; index < 3; ++index) {
            rc.emplace(std::string(name[index]), index+1);
        }
        return rc;
    }
}
std::map<std::string, int> const A::m_name2code = build_map();

如果你想更加想象,你甚至可以在编译时使用std::map初始化地图(虽然不是constexpr)(参见,例如,我的CppCon 2016年演示文稿:Constant Fun)。

以上是关于如何使用C ++中的某个语句初始化类const static结构的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 if 语句比较 laravel 数据库中的值?

如何在Obj C中的另一个类中使用一个类中声明的变量

如何使用 Spring Framework 中的 JdbcTemplate 类执行 INSERT 语句

c++ - 如何使用构造函数中的'this'初始化其他类中的引用

如何使用 CSS 选择器使用 BeautifulSoup 检索位于某个类中的特定链接?

c语言如何删除数组中的某个元素