我正在用 C++ 创建一个蛇游戏,但在使用我创建的 linkedList 类时遇到了一些问题。当我用 Python 制作蛇时,我在列表中创建了列表来表示构成蛇的每个圆圈的 x 和 y 位置。我正在尝试在 C++ 中做类似的事情。这是我制作的模板化 linkedList 类,如果出于某种原因您需要查看它:
#ifndef LLIST_H_INCLUDED
#define LLIST_H_INCLUDED
#include <cstddef>
#include <iostream>
using namespace std;
template <class T>
class linkedList
{
public:
class node
{
public:
///node class attributes
T mPayload;
node* mNext;
///constructor
node(T toucan):mPayload(toucan),mNext(NULL)
{}
///destructor
~node()
{
///cascading delete
if(mNext)
delete mNext;
}
///node class methods
};
///linkedList class attributes
node* mStart;
///constructor
linkedList():mStart(NULL)
{}
///destructor
~linkedList()
{
///initializes the cascading delete.
if(mStart)
delete mStart;
}
///linkedList class methods
T mReturnT(int indx)
{
if(!mStart)
return NULL;
else
{
node* cur;
for(int i = 0; i<indx; i++)
{
if(!cur->mNext)
{
cout << "Indx out of range. Deleting last item." << endl;
break;
}
cur = cur->mNext;
}
delete cur;
return cur->mPayload;
}
}
void mInsert(int indx, T data)
{
///Insert an item at a given position.
///The first argument is the index of
///the element before which to insert.
node* cur = mStart;
for(int i = 0; i < indx; i++)
{
if(!cur->mNext)
break;
else
{
cur = cur->mNext;
}
}
node* N = new node(data);
node* temp = cur->mNext;
cur->mNext = N;
N->mNext = temp;
}
T mPop()
{
///Removes the last item in the list,
///and returns it.
if(!mStart)
return NULL;
else
{
node* cur = mStart;
while(cur->mNext)
{
cur = cur->mNext;
}
T var = cur->mPayload;
delete cur;
return var;
}
}
int mSize()
{
if(!mStart)
return 0;
else
{
node* cur = mStart;
int counter = 1;
while(cur->mNext)
{
cur = cur->mNext;
counter++;
}
delete cur;
return counter;
}
}
void mPrint()
{
///prints all values in a list.
node* cur;
if(!mStart)
cout << "List is empty." << endl;
else
{
cur = mStart;
cout << "[";
while(cur)
{
cout << cur->mPayload << " ";
cur = cur->mNext;
}
cout << "]" << endl;
delete cur;
}
}
void swapNodes(node* N)
{
///idk
}
void bubbleSort()
{
if(!mStart)
return;
node* cur = mStart;
while(cur)
{
cout << cur->mPayload << endl;
if(cur->mRight->mFrequency > cur->mFrequency)
{
swapNodes(cur);
cur = mStart;
}
else
cur = cur->mRight;
}
delete cur;
}
};
#endif // LLIST_H_INCLUDED
现在在我的 main.cpp 中,我想做这样的事情,以便我有一个链表的链表:
linkedList<linkedList> p1Snake;
linkedList<int> startingPiece;
startingPiece.mInsert(0,600); //This is the starting y position of
// p1snake added to the front of the list.
startingPiece.mInsert(0,350); //This is the starting x position of
//p1snake added to the front of the list.
p1Snake.mInsert(0,startingPiece);
我的问题出现在该代码的第一行。错误:“模板类链接列表”的模板参数列表中的参数 1 处的类型/值不匹配。我该如何解决这个问题?
最佳答案
你的lnkedList
类有1个模板化类型T
,所以变量定义的语法应该是:
linkedList<type> variableName;
通过递归,type
可以是linkedList
,但它仍然应该是上面的形式(有type
)。
例如,如果最后一个数据类型是 int
:
linkedList<linkedList<int> > variableName;
关于c++ - 如何在链接列表中创建链接列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20715657/