在C ++中初始化一个const字符串的静态const数组 [英] Initializing a static const array of const strings in C++
问题描述
我无法初始化常量字符串的常数数组。
I am having trouble initializing a constant array of constant strings.
从week.h(仅显示相关部分):
From week.h (showing only relevant parts):
class Week {
private:
static const char *const *days = { "mon", "tue", "wed", "thur",
"fri", "sat", "sun" };
};
当我编译时,我得到错误标量初始化器中的多余元素。我试着让它类型const char **,认为我搞砸了第二个const的位置,但我有同样的错误。
When I compile I get the error "excess elements in scalar initializer". I tried making it type const char **, thinking I messed up the 2nd const placement, but I got the same error. What am I doing wrong?
推荐答案
首先,你需要一个数组,而不是指针。
First of all, you need an array, not a pointer.
static const char * const days[] = {"mon", "tue", "wed", "thur",
"fri", "sat", "sun"};
其次,你不能直接在类定义内部初始化。 Iside类的定义,只留下:
Second of all, you can't initialize that directly inside the class definition. Iside the class definition, leave only this:
static const char * const days[]; //declaration
然后,在.cpp文件中写入定义
Then, in the .cpp file, write the definition
const char * const Week::days[] = {"mon", "tue", "wed", "thur",
"fri", "sat", "sun"};
这篇关于在C ++中初始化一个const字符串的静态const数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!