编辑:请注意,正如 @ThomasMatthews 答案中所述,最好不要将数据放入标头中。请参考他的回答。
我想在类的头文件中创建一个 static const char* const 数组。例如:const static char* ar[3] = {"asdf","qwer","ghjk"};但是我收到错误。
这是一个例子:
#include <iostream>
class test{
static const char* const ar[3] = {"asdf","qwer","hjkl"};
}
int main(){}
Run Code Online (Sandbox Code Playgroud)
这是错误:
static data member of type 'const char *const [3] must be initialized out of line
Run Code Online (Sandbox Code Playgroud)
我想知道我想做的事情是否可行。我读过在类定义中定义静态常量整数成员,我从中得到的印象是只能用 int 来做到这一点。如果这是相关的,我使用的是 mac,我的 g++ 版本如下:
Apple LLVM version 9.1.0 (clang-902.0.39.1)
Target: x86_64-apple-darwin17.5.0
Thread model: posix
Run Code Online (Sandbox Code Playgroud)
为静态类成员提供单独的外线定义(带有初始值设定项)的需要源于这样一个事实:C++ 中定义的确切点会影响初始化的顺序以及导出符号在目标文件中的位置。该语言希望您自己做出这些决定。
但是,为了在您不关心此类内容的常见情况下简化事情,从 C++17 开始,您可以通过inline在静态成员声明中指定显式关键字来完全执行您想要的操作
class test{
static inline const char* const ar[] = { "asdf", "qwer", "hjkl" };
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4709 次 |
| 最近记录: |