简体   繁体   English

在 C++ 中初始化一个静态成员(一个数组)

[英]Initialize a static member ( an array) in C++

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]?你将如何初始化 a[128]? Why can't I initialize a[128] by directly specifying its value like in C?为什么我不能像在 C 中那样通过直接指定其值来初始化 a[128]?

a[128] = {1,2,3,...};

您可以,只需在您的 .cpp 文件中执行此操作:

char A::a[6] = {1,2,3,4,5,6};

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将其全部保留在类定义中:

class A
{
public:
  static constexpr const char a[] = {1,2,3}; // = "Hello, World"; would also work
  static void do_something();
};

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', '\0' };
Member MyClass::m_( 5 );

好吧,我发现了一种不同的初始化方法,而无需在已经是意大利面条的 C++ 中创建额外的项目

char fred::c[4] = {};

With C+++17 and up, you can initialize it inline, as follows使用C+++17及更高版本,您可以对其进行内联初始化,如下所示

class A
{
public:
  inline static char a[2]={1,1};
  static void do_something();
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM