2
我试图为List类创建自己的模板作为学习练习。我一直有一些麻烦的模板语法,虽然现在我得到以下错误消息..错误:'struct List'需要模板参数
main.cpp|Line 8|instantiated from here
error: template argument required for 'struct List'
In function 'int main()':
...
至于我可以告诉我不是滥用什么,但,这是我第一次与合作模板,并会真正感谢有人翻阅并让我知道我做错了什么。
List.hpp:
#if !defined _LIST_HPP_
#define _LIST_HPP_
#include "Node.hpp"
///since we're creating a template everything must be defined in the hpp
template <typename ListType>
class List
{
public:
List();
bool Empty();
void PushFront();
void PushBack();
void PopBack();
Node<ListType>& GetHead();
private:
int _size;
Node<ListType>* _head;
Node<ListType>* _tail;
};
///implement List class here
template <typename ListType>
List<ListType>::List() : _head(0), _tail(0), _size(0)
{
}
template <typename ListType>
bool List<ListType>::Empty()
{
return _size == 0;
}
template <typename ListType>
void List<ListType>::PushFront()
{
_head = new Node<ListType>(_head , 0);
if (!Empty())
_head->_prev->_next = _head; //set previous nodes _next to new _head
++_size;
}
template <typename ListType>
void List<ListType>::PushBack()
{
_tail = new Node<ListType>(0 , _tail);
if (!Empty())
_tail->_next->_prev = _tail; // set old tails _prev to new tail
++_size;
}
template <typename ListType>
void List<ListType>::PopBack()
{
}
template <typename ListType>
Node<ListType>& List<ListType>::GetHead()
{
return _head;
}
#endif //define
Node.hpp:
#if !defined _NODE_HPP_
#define _NODE_HPP_
template<typename NodeType>
class Node{
public:
Node(Node* prev = 0, Node* next = 0);
void SetData(NodeType newData);
void GetData();
private:
friend class List;
NodeType _data;
Node* _next;
Node* _prev;
};
///implement Node
template <typename NodeType>
Node<NodeType>::Node(Node* prev, Node* next) : _prev(prev), _next(next)
{}
template <typename NodeType>
void Node<NodeType>::SetData(NodeType newData)
{
_data = newData;
}
template <typename NodeType>
void Node<NodeType>::GetData()
{
return _data;
}
#endif //define
Main.hpp
#include <iostream>
#include "List.hpp"
int main()
{
List<int> testl;
//test
testl.PushFront();
testl.GetHead().SetData(7); //Error thrown here??
std::cout << test1.GetHead().GetData() << std::endl;
return 0;
}
啊谢谢你会花费我很多时间来弄清楚。你能否扩展你的第三点?也许把它插入我的代码?听起来很厚道,但我无法编译它。如果我把节点声明之外的代码的最后一节放在节点声明之外,那么“friend”语法就不好,如果我把它放在节点类里面,它说“列表不是一个模板”就行'friend class List; '。你也确定typename在上面是正确的吗?只是检查,就像我说的,我还没有真正熟悉模板语法。真的很感谢回应! –
Holly
2012-03-24 10:23:28
说一个谎言,实际上是能够通过使上面第一个变化得到它的工作'template friend class List;'..不会介意关于后期的更多信息,我有麻烦了,但否则我的程序工作正常:)谢谢! –
Holly
2012-03-24 11:08:18