这与其他一些问题有关,例如:this https://stackoverflow.com/questions/34987/how-to-declare-an-array-of-strings-in-c,以及我的其他一些问题。
In 这个问题 https://stackoverflow.com/questions/34987/how-to-declare-an-array-of-strings-in-c以及其他,我们看到我们可以通过一个很好的步骤来声明和初始化字符串数组,例如:
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
}
};
但是,编译器会抱怨,我似乎无法弄清楚为什么。是否可以在类定义中一步声明并初始化这样的数组?有更好的替代方案吗?
使用关键字 static 和外部初始化使数组成为类的静态成员:
在头文件中:
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"};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)