C++ 编译错误:意外的类型名称"字符串":预期的表达式

c++ compile error: unexpected type name 'string': expected expression

本文关键字:表达式 字符串 类型 编译 错误 意外 C++      更新时间:2023-10-16

我想使用 c++ stl list 并使用迭代器打印所有元素。这是代码:

#include<list>
#include<algorithm>
#include<string>
using namespace std;
int main(int argc, char* argv[]){
list<string> list;
//list<double> list_double(6);
//list<int> list_int(6, 0);
//list<double> list_double2(6, 0,0);
//list<int> else_list(list_int);
//list<double> iter(list_double.begin(), list_double.end());
list.push_front("1 jack");
list.push_front("2 jackson");
list.push_front("3 sally");
list<string>::iterator itrr;
for (itrr = list.begin(); itrr!= list.end(); itrr++){
string temp = *itrr;
print(temp)nt main(int argc, char* argv[]){
list<string> list;
//list<double> list_double(6);
//list<int> list_int(6, 0);
//list<double> list_double2(6, 0,0);
//list<int> else_list(list_int);
//list<double> iter(list_double.begin(), list_double.end());
list.push_front("1 jack");
list.push_front("2 jackson");
list.push_front("3 sally");
list<string>::iterator itrr;
for (itrr = list.begin(); itrr!= list.end(); itrr++){
string temp = *itrr;
print(temp);
}
return 0;
}

}
return 0;
}

当我尝试编译它时,它显示一些错误:

list.cpp:17:7: error: unexpected type name 'string': expected expression
list<string>::iterator itrr;
^
list.cpp:17:16: error: cannot refer to class template 'iterator' without a template argument list
list<string>::iterator itrr;
~~^
/Library/Developer/CommandLineTools/usr/include/c++/v1/iterator:522:29: note: template is declared here
struct _LIBCPP_TEMPLATE_VIS iterator
^
list.cpp:18:7: error: use of undeclared identifier 'itrr'
for (itrr = list.begin(); itrr!= list.end(); itrr++){
^
list.cpp:18:28: error: use of undeclared identifier 'itrr'
for (itrr = list.begin(); itrr!= list.end(); itrr++){
^
list.cpp:18:47: error: use of undeclared identifier 'itrr'
for (itrr = list.begin(); itrr!= list.end(); itrr++){
^
list.cpp:19:18: error: use of undeclared identifier 'itrr'
string temp = *itrr;
^

那么出了什么问题呢?谢谢!

问题

list<string> list;

将标识符list定义为类型list<string>的变量。这将替换以前将标识符list定义为标准库std::list类。这意味着当编译器在代码的许多后续点达到list<string>时,list<string>毫无意义。<string>与您可以对变量执行的任何操作都不匹配。

溶液

注意如何重用标识符。制作名为listlist会给读者和编译器带来混淆,所以不要这样做。为变量指定不同的名称。它充满了名字,所以为什么不namelist?

这个问题与using namespace std;的危险相吻合。有关此内容的更多信息,请阅读为什么"使用命名空间 std"被认为是不好的做法?