无法解析C++中的标识符 [方法] 名称

unable to resolve identifier [method] names in C++

本文关键字:标识符 方法 名称 C++      更新时间:2023-10-16

所以我对编程并不陌生,但是是的,我对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[]数组传递给具有数组大小的函数

这是我在回答的开头完成的