[英]How to initialize a class variable using a for loop in C++?
我的示例 class 有一個 static 字符數組,我想創建一個從字符到索引的 map。 我需要在我的“example.cpp”文件中的 for 循環中初始化這個 static map。 然而,C++“期待聲明”。 有什么辦法可以將我的 map 作為聲明填寫嗎? 通常,是否可以在調用 class 變量的構造函數之前為 static 變量創建一個處理所有這些初始化的構造函數?
這是我的示例 class。
#include <map>
using namespace std;
class Example {
static char chars[4];
static map<char,int> char2idx;
};
char Example::chars[4] = {'a','b','c','d'};
for(int i=0; i<4;i++) {
Example::char2idx[Example::chars[i]] = i;
}
當我嘗試編譯時出現以下錯誤。
clang++ -std=c++11 -Wall -g -c -o example.o example.cpp
example.cpp:9:1: error: expected unqualified-id
for(int i=0; i<4;i++) {
^
1 error generated.
快速修復:做一個幫手 function
#include <map>
using namespace std;
class Example {
friend map<char,int> helper(); // so it can see the private members
static char chars[4];
static map<char,int> char2idx;
};
map<char,int> helper() // does the work, returns the map
{
map<char,int> out;
// for(int i=0; i<4;i++) { that four is ugly. What if chars changes in size?
for(int i=0; i<std::size(Example::chars);i++) { // if we didn't want i I'd use
// a range-based for to make
// life even simpler.
out[Example::chars[i]] = i;
}
return out; // return by value. copy elision is your friend!
}
char Example::chars[4] = {'a','b','c','d'};
map<char,int> Example::char2idx = helper();
C++ 中的 ur-example 是如何初始化std::cin
、 std::cout
等的。 核心技巧是在調用 static 構造函數的全局命名空間中有一個本地 static 變量:
example.hpp
class Example
{
static stuff here;
static bool initialize();
};
static bool b_initialize_Example = Example::initialize();
example.cpp
bool Example::initialize()
{
static bool is_initialized = false;
if (!is_initialized)
{
// do your for loop here.
}
return is_initialized = true;
}
另一種方法是使用工廠生成 class 的實例。第一次生成實例時,初始化 static 數據。
// No example here. Google around factory methods.
// You’ll still need a static bool is_initialized somewhere.
最后,您可以在類的構造函數中只使用 static 初始值設定項。 這類似於第一種方法:
class Example
{
Example() { initialize(); ... }
static void initialize()
{
static bool is_initialized = false;
if (is_initialized) return;
// initialize stuff here
is_initialized = true;
}
};
我敢肯定還有其他方法可以解決這個問題 go ,但這就是我的想法。
編輯:另一個答案中的例子也很好!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.