【问题标题】:Sorted lists in C++C++中的排序列表
【发布时间】:2018-08-06 12:53:32
【问题描述】:

我正在学习数据结构课程并被要求创建一个排序列表,但是每当我尝试声明使用数据类型的变量时都会出错。 这是我到目前为止所做的事情

#include<iostream>

using namespace std;
int main(){
  List<int> x;
  // Other Code for testing
}
const int MAX_ITEMS = 30;
template<class T>
class List{
private:
  int size;
  int currIndex;
  T data[MAX_ITEMS];
public:
    // list functions
};

但是在编译时出现错误:

$ g++ sortedList.cpp
sortedList.cpp:5:3: error: use of undeclared identifier 'List'
  List<int> x;
  ^
sortedList.cpp:5:11: error: expected '(' for function-style cast or type
      construction
  List<int> x;

错误在于List&lt;int&gt; x;这一行,这不是我们应该如何使用模板声明变量吗?

完整代码可以在这里找到:https://pastebin.com/T2hXDxAP

【问题讨论】:

  • main()移动到底部。
  • C++ 需要前向声明。将您的List 定义移动到main 之上,最好是在它自己的头文件中。

标签: c++ list data-structures


【解决方案1】:

假设你是编译器。您正在从上往下读取文件,您会遇到这样的情况:

List<int> x;

当编译器看到这个时,它会:

WTF!我以前从未见过。是标识符吗?让我检查一下……不!在mainmain 之前什么都没有!随机乱码?是的,让我们创建一个错误!

因此编译器会产生错误。要解决此问题,您需要在main 之前定义类。 (不能转发声明类,因为它是一个模板,需要在使用前定义更多信息可以找到here)。

【讨论】:

  • 很好的解释.. 谢谢!
猜你喜欢
  • 2011-07-31
  • 2011-04-12
  • 1970-01-01
  • 1970-01-01
  • 2011-09-30
  • 1970-01-01
  • 1970-01-01
  • 2011-10-29
相关资源
最近更新 更多