这是我所拥有的(不工作)的简化版本:
程序.h:
...
const string c_strExample1 = "ex1";
const string c_strExample2 = "ex2";
const string c_astrExamples[] = {c_strExample1, c_strExample2};
...
程序.cpp:
...
int main()
{
int nLength = c_astrExamples.length();
for (int i = 0; i < nLength; i++)
cout << c_astrExamples[i] << "\n";
return 0;
}
...
当我尝试构建时,出现以下错误: error C2228: '.length' 的左边必须有类/结构/union
错误仅在我尝试使用 c_astrExamples 的成员函数时发生。 如果我用数字 2 替换“c_astrExamples.length()”,一切似乎都正常工作。
我能够使用 c_strExample1 和 c_strExample2 的成员函数,所以我认为这种行为是由于我使用字符串与字符串数组之间的一些差异所致。
我在prog.h 中的初始化错误吗?我需要在 prog.cpp 中添加一些特殊的东西吗?
最佳答案
C++ 中的数组没有成员函数。您应该使用像 vector<string>
这样的集合如果你想要一个对象,或者像这样计算长度:
int nLength = sizeof(c_astrExamples)/sizeof(c_astrExamples[0]);
关于c++ - 如何在 C++ 中使用常量数组的成员函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1639393/