这与其他一些问题有关,例如:this以及我的其他一些问题。
在this question和其他人中,我们看到我们可以在一个很好的步骤中声明和初始化字符串数组,例如:
const char* const list[] = {"zip", "zam", "bam"}; //from other question
这可以在没有麻烦的函数的实现中完成,也可以在任何范围之外的.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
}
};
但是,编译器抱怨并且我似乎无法找出原因。是否可以在类定义的一个步骤中声明和初始化这样的数组?是否有更好的替代方案?
我确信这是一个非常业余的错误,但一如既往,非常感谢您的帮助和建议。
干杯,
XAN
答案 0 :(得分: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
}
};
在.cpp文件中:
const char* const DataProvider::mStringData[] = {"Name1", "Name2", "Name3", ... "NameX"};
答案 1 :(得分:3)
这在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);
}
};
请注意,您必须放弃数组中指针的常量,因为您无法直接初始化数组。但是你需要稍后将指针设置为正确的值,因此指针需要是可修改的。
如果数组中的值是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" };
拥有静态数组意味着所有对象都将共享该数组。因此,你也会保存记忆。
答案 2 :(得分:3)
你无法像这样声明你的数组(const char * [])的原因是:
const char* []
没有说明编译器需要为每个实例分配多少空间(您的数组被声明为实例变量)。此外,您可能希望将该数组设为静态,因为它实质上是一个常量值。