无法解析C++中的标识符 [方法] 名称
unable to resolve identifier [method] names in C++
所以我对编程并不陌生,但是是的,我对C++是新手。
我在 Next()
方法中收到此错误,突出显示了names[]
数组。有人可以帮忙吗?
typedef string text;
text Next(text t);
int main() {
text rock;
text names[10] = {"basalt", "dolomite", "granite", "gypsum", "limestone", "marble",
"obsidian", "quartzite", "sandstone", "shale"};
cout<<"Enter a rock: n";
cin>>rock;
cout<<Next(rock);
return 0;
}
text Next(text t) {
for (int i = 0; i < 10; i++) {
if (names[i].compare(t) == 0) {
return names[i + 1];
}
}
return "Off boundary or not found";
}
试试这个,它应该有希望工作。我在最后一行代码中添加了一些解释。
typedef string text;
text Next(text t, text namesArr[], int size); // modified
int main() {
text rock;
text names[10] = {"basalt", "dolomite", "granite", "gypsum", "limestone", "marble", "obsidian", "quartzite", "sandstone", "shale"};
cout<<"Enter a rock: n";
cin>>rock;
cout<<Next(rock, names, 10); // modified
return 0;
}
text Next(text t, text namesArr[], int size) { // modified
for (int i = 0; i < size; i++) {
if (namesArr[i].compare(t) == 0) {
if (i==9) {
return namesArr[0];
}
else {
return namesArr[i + 1];
}
}
}
return "Not found"; // modified , it should never be out of bound since you specify the fixed array size, and also because you do the checking i==9
}
代码中的问题是text names[10]
是在函数main()
中定义的。因此,此数组仅是主函数的本地数组。
如果您想在Next()
函数中使用数组,您可以
1. 使names[]
数组全局化,即
typedef string text;
text Next(text t);
// defined globally here, any function can now access this array.
text names[10] = {"basalt", "dolomite", "granite", "gypsum", "limestone", "marble", "obsidian", "quartzite", "sandstone", "shale"};
int main() {
// your original code here, without the "names[]" declaration.
}
text Next(text t) {
// your code here, but with the "i==9" case checking to prevent out of bound
}
2. 将names[]
数组传递给具有数组大小的函数
这是我在回答的开头完成的
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 通过方法访问结构
- 最小硬币更换问题(自上而下方法)
- C++为构建时间获取QDateTime的可靠方法
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 处理多个异常集合的C++方法
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 有什么方法可以遍历结构吗
- 当类在C++中定义时,有什么方法可以"register"类吗?
- 无法解析C++中的标识符 [方法] 名称
- 模板取消排队方法具有未声明的标识符
- 视觉 在调用它时用 c++ 创建一个方法后,我得到的错误标识符未找到
- 有没有一种方法可以在枚举中使用关键字作为标识符
- 为什么这个依赖名称查找查找的是全局标识符而不是方法
- C++-有没有一种方法可以将标识符作为字符串
- 是否有一种方法可以禁用C头文件中的全局标识符
- 映射<someKey、map<otherKey、标识符> >的替代方法
- 测试标识符没有被截断从而混淆的好方法是什么?
- 是否有一种方法可以强制OpenGL标识符从1开始而不是0