【问题标题】:Compiler error with list<string>list<string> 的编译器错误
【发布时间】:2011-03-19 20:55:27
【问题描述】:

我正在尝试按照示例here 创建一个字符串列表。下面给了我语法错误:

private: list<string> images;

错误(都在上面声明所在的那一行):

syntax error : missing ';' before '<'
missing type specifier - int assumed. Note: C++ does not support default-int
unexpected token(s) preceding ';'

它在一个只有一个构造函数的类中,没有它也可以正常编译。我做错了什么?

【问题讨论】:

  • 你可能不想要list,而是vector
  • 发布代码有助于追踪错误。

标签: c++ string list stl managed-c++


【解决方案1】:

你是#include&lt;list&gt;&lt;string&gt;吗?另外,您是否通过编写任一方式从namespace std 导入了名称liststring

using namespace std;

using std::list;   using std::string;

您遇到的错误与无法访问的名称一致,所以这是我的最佳猜测。

编辑:由于这是在头文件中,因此您不应该使用上述任何一种结构(感谢 wilhelmtell 指出这是一个头文件!)。相反,您应该将名称完全限定为

private: std::list<std::string> images;

这样编译器就知道在哪里寻找liststring

【讨论】:

  • 不要将命名空间std 带入标题中!
  • @wilhelmtell- 天哪!没想到是个头。答案已适当更新。
  • @wilhelmtell 那么为什么不应该将命名空间带入标题中呢?
  • @quasiserve- 如果您在标头中有using namespace 声明,则包含该标头的任何文件都会将该名称空间中的所有名称隐式导入其全局名称空间。这可能会导致无意的名称冲突,并且很难追查到,因为问题的根源深藏在标题中。对于此名称,通常认为在标头中使用完全限定名称而不是 using namespace 声明是个好主意。
【解决方案2】:

您需要使用namespace 来限定liststring 类型。

#include &lt;string&gt;#include &lt;list&gt; 指令之后输入std::list&lt;std::string&gt; 或添加using namespace std;

一个简单的工作程序:

#include <list>
#include <string>
using namespace std;
int main ( int, char ** )
{
    list<string> strings;
    strings.push_back("1st string");
}

【讨论】:

  • 我使用了限定名,这是我现在得到的错误:cannot define 'images' as a member of managed 'MyClass::MyForm': mixed types are not supported
  • @Igor:托管 C++ 与 C++ 不同,您应该相应地标记您的问题。
猜你喜欢
  • 1970-01-01
  • 2014-12-27
  • 2015-11-25
  • 1970-01-01
  • 1970-01-01
  • 2022-11-01
  • 2018-01-19
  • 1970-01-01
  • 2014-11-19
相关资源
最近更新 更多