对于我的 C++ 课程的家庭作业,我必须创建一个链表数据结构。我现在有两节课。List 类(它是一个模板类)和 Link 类。Link 类嵌套在 List 类中,但是,我试图在单独的头文件中定义它。我遇到的问题来自我对链接过程的工作原理缺乏了解。这就是我所拥有的。
List.h 的内容
#ifndef _LIST_H_
#define _LIST_H_
template <class T>
class List
{
protected:
class Link;
public:
List() : _head(nullptr) { }
~List() { }
void PushFront(T object)
{
// !! Attention !!
// When I uncomment this line I get the error:
// error C2514: 'List<T>::Link' : class has no constructors...
// My problem is the compiler doesn't know what Link is yet (I'm assuming).
//_head = new Link(object, _head);
}
protected:
Link* _head;
};
#endif // _LIST_H_
Link.h 的内容
#ifndef _LINK_H_
#define _LINK_H_
#include "List.h"
template <class T>
class List<T>::Link
{
public:
Link(T object, Link* next = nullptr)
: _object(object), _next(next) { }
~Link() { }
private:
T _object;
Link* _next;
};
#endif // _LINK_H_
main.cpp 的内容(入口点)
#include "List.h"
int main()
{
int b = 5;
List<int> a;
a.PushFront(b); // If I comment this line, then the code compiles fine.
}
我确定这是正在发生的链接错误。类似于我在微软网站上查找的这个错误(http://msdn.microsoft.com/en-us/library/4ce3zbbc.aspx),但是,我不确定如何解决它。