你如何在 C++ 头文件中声明数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/284833/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 14:21:14  来源:igfitidea点击:

How do you declare arrays in a c++ header?

c++arraysheaderinitializationconst

提问by xan

This is related to some other questions, such as: this, and some of my other questions.

这与其他一些问题有关,例如:this和我的一些其他问题。

In this question, and others, we see we can declare and initialise string arrays in one nice step, for example:

这个问题和其他问题中,我们看到我们可以在一个不错的步骤中声明和初始化字符串数组,例如:

const char* const list[] = {"zip", "zam", "bam"}; //from other question

This can be done in the implementation of a function with no bother, or in the body of a .cpp file, outside any scope.

这可以在没有麻烦的函数的实现中完成,或者在任何范围之外的 .cpp 文件的正文中完成。

What I want to do is to have an array like this as as member of a class I am using, something like this:

我想要做的是将这样的数组作为我正在使用的类的成员,如下所示:

class DataProvider : public SomethingElse
{
    const char* const mStringData[] = {"Name1", "Name2", "Name3", ... "NameX"};

public:
    DataProvider();
    ~DataProvider();

    char* GetData()
    {
        int index = GetCurrentIndex(); //work out the index based on some other data
        return mStringData[index]; //error checking and what have you omitted
    }

};

But, the compiler complains and I can't seem to work out why. Is it possible to declare and initialise an array like this in one step in a class definition? Are there alternatives that are better?

但是,编译器抱怨,我似乎无法弄清楚原因。是否可以在类定义的一个步骤中声明和初始化这样的数组?有没有更好的替代品?

采纳答案by Stefan R?dstr?m

Use the keyword static and external initialization to make the array a static member of the class:

使用关键字 static 和外部初始化使数组成为类的静态成员:

In the header file:

在头文件中:

class DataProvider : public SomethingElse
{
    static const char* const mStringData[];

public:
    DataProvider();
    ~DataProvider();

    const char* const GetData()
    {
        int index = GetCurrentIndex(); //work out the index based on some other data
        return mStringData[index]; //error checking and what have you omitted
    }

};

In the .cpp file:

在 .cpp 文件中:

const char* const DataProvider::mStringData[] = {"Name1", "Name2", "Name3", ... "NameX"};

回答by Johannes Schaub - litb

This is not possible in C++. You cannot directly initialize the array. Instead you have to give it the size it will have (4 in your case), and you have to initialize the array in the constructor of DataProvider:

这在 C++ 中是不可能的。您不能直接初始化数组。相反,您必须为其指定大小(在您的情况下为 4),并且您必须在 DataProvider 的构造函数中初始化数组:

class DataProvider {
    enum { SIZEOF_VALUES = 4 };
    const char * values[SIZEOF_VALUES];

    public:
    DataProvider() {
        const char * const v[SIZEOF_VALUES] = { 
            "one", "two", "three", "four" 
        };
        std::copy(v, v + SIZEOF_VALUES, values);
    }
};

Note that you have to give up on the const-ness of the pointers in the array, since you cannot directly initialize the array. But you need to later set the pointers to the right values, and thus the pointers need to be modifiable.

请注意,您必须放弃数组中指针的常量性,因为您无法直接初始化数组。但是您稍后需要将指针设置为正确的值,因此指针需要是可修改的。

If your values in the array are const nevertheless, the only way is to use a static array:

如果数组中的值仍然是 const,唯一的方法是使用静态数组:

/* in the header file */
class DataProvider {
    enum { SIZEOF_VALUES = 4 };
    static const char * const values[SIZEOF_VALUES];
};

/* in cpp file: */

const char * const DataProvider::values[SIZEOF_VALUES] = 
    { "one", "two", "three", "four" };

Having the static array means all objects will share that array. Thus you will have saved memory too.

拥有静态数组意味着所有对象都将共享该数组。因此,您也将节省内存。

回答by Carl Seleborg

The reason you can't declare your array like that (const char* []) is that:

您不能像这样声明数组的原因 (const char* []) 是:

  • you can't have initializers in the class declaration, and so
  • the syntax const char* []does not state how much space the compiler needs to allocate for each instance (your array is declared as instance variable).
  • 你不能在类声明中使用初始化器,所以
  • 语法const char* []没有说明编译器需要为每个实例分配多少空间(您的数组被声明为实例变量)。

Besides, you probably want to make that array static, since it is in essence a constant value.

此外,您可能希望将该数组设为静态,因为它本质上是一个常量值。