在 C++ 中初始化一个静态成员(一个数组)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2570235/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Initialize a static member ( an array) in C++
提问by vtd-xml-author
I intended to create a class which only have static members and static functions. One of the member variable is an array. Would it be possible to initialize it without using constructors? I am having lots of linking errors right now...
我打算创建一个只有静态成员和静态函数的类。成员变量之一是数组。是否可以在不使用构造函数的情况下对其进行初始化?我现在有很多链接错误...
class A
{
public:
static char a[128];
static void do_something();
};
How would you initialize a[128]? Why can't I initialize a[128] by directly specifying its value like in C?
你将如何初始化 a[128]?为什么我不能像在 C 中那样通过直接指定其值来初始化 a[128]?
a[128] = {1,2,3,...};
回答by Brian R. Bondy
You can, just do this in your .cpp file:
您可以,只需在您的 .cpp 文件中执行此操作:
char A::a[6] = {1,2,3,4,5,6};
回答by jasonline
Just wondering, why do you need to initialize it inside a constructor?
只是想知道,为什么需要在构造函数中初始化它?
Commonly, you make data member static so you don't need to create an instance to be able to access that member. Constructors are only called when you create an instance.
通常,您将数据成员设为静态,因此您无需创建实例即可访问该成员。构造函数仅在您创建实例时调用。
Non-const static members are initialized outside the class declaration (in the implementation file) as in the following:
非常量静态成员在类声明之外(在实现文件中)初始化,如下所示:
class Member
{
public:
Member( int i ) { }
};
class MyClass
{
public:
static int i;
static char c[ 10 ];
static char d[ 10 ];
static Member m_;
};
int MyClass::i = 5;
char MyClass::c[] = "abcde";
char MyClass::d[] = { 'a', 'b', 'c', 'd', 'e', 'class A
{
public:
static constexpr const char a[] = {1,2,3}; // = "Hello, World"; would also work
static void do_something();
};
' };
Member MyClass::m_( 5 );
回答by Ben Hershey
If your member isn't going to change after it's initialized, C++11 lets you keep it all in the class definition with constexpr
:
如果您的成员在初始化后不会更改,C++11 允许您将其全部保留在类定义中constexpr
:
char fred::c[4] = {};
回答by Vijay Kumar Kanta
Well, I have found out a different way to initialize without resorting to create additional items in the already spaghetti C++
好吧,我发现了一种不同的初始化方法,而无需在已经是意大利面条的 C++ 中创建额外的项目
##代码##