Initializing a static const array of const strings in C++(在 C++ 中初始化 const 字符串的静态 const 数组)
问题描述
我在初始化常量字符串的常量数组时遇到问题.
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"};
其次,你不能直接在类定义中初始化它.在类定义中,只保留以下内容:
Second of all, you can't initialize that directly inside the class definition. Inside 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++11 更新现在您可以直接在类定义中初始化成员:
Update for C++11 Now you can initialize members directly in the class definition:
const char * const days[] = {"mon", "tue", "wed", "thur",
"fri", "sat", "sun"};
这篇关于在 C++ 中初始化 const 字符串的静态 const 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C++ 中初始化 const 字符串的静态 const 数组
基础教程推荐
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 初始化列表*参数*评估顺序 2021-01-01
- CString 到 char* 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
