如何在c ++头中声明数组?

xan*_*xan 22 c++ arrays initialization const header

这与其他一些问题有关,例如:这个,以及我的一些其他问题.

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

const char* const list[] = {"zip", "zam", "bam"}; //from other question
Run Code Online (Sandbox Code Playgroud)

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

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

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
    }

};
Run Code Online (Sandbox Code Playgroud)

但是,编译器抱怨并且我似乎无法找出原因.是否可以在类定义的一个步骤中声明和初始化这样的数组?有更好的替代方案吗?

我确信这是一个非常业余的错误,但一如既往,我非常感谢你的帮助和建议.

干杯,

XAN

Ste*_*röm 18

使用关键字static和external initialization使数组成为类的静态成员:

在头文件中:

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
    }

};
Run Code Online (Sandbox Code Playgroud)

在.cpp文件中:

const char* const DataProvider::mStringData[] = {"Name1", "Name2", "Name3", ... "NameX"};
Run Code Online (Sandbox Code Playgroud)

  • 是的,我认为省略大小是有效的,那么阵列是不完整的.但是在标题中,你确实不知道数组的大小.所以也没有尺寸可能---- (2认同)