c++ - 如何在 C++ 中使用常量数组的成员函数?

标签 c++ arrays constants

这是我所拥有的(不工作)的简化版本:

程序.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/

相关文章:

c++ - 关于 sizeof 运算符的困惑

java - 添加 StringArrayOfNumbers 的输出未按预期输出

带有嵌套循环的 Javascript 嵌套数组

arrays - 无法将字符串 append 到 Swift 中的可变数组

c++ - 将<shared_ptr<T>>::iterator 设置为<shared_ptr<T const>>::const_iterator

C: 将 "static const char * const"分配给 "static const char *"

unit-testing - 将常量添加到 PHPUnit 中的模拟

c++ 运行时库选项

c++ - 不是root时Semget权限被拒绝,服务器配置问题?

c++ - 为什么 QMediaGaplessPlaybackControl 不存在?