我尝试在c ++中结合模板构建一个双重连接的列表。
如果我尝试编译Programm,Visual Studio会抛出一个
C2676错误:二进制运算符" ++":Interator"没有定义或 不会将此运算符转换为可用类型
为什么这不起作用?如果我添加另一个方法来执行相同的操作,如我的重载增量器,它工作正常,但如果我重载增量器,它会抛出我的错误。
这里有一些代码:
我的NodeElement类:
template<typename T>
class Nodeelement
{
public:
Nodeelement(T data)
{
this->data = data;
pNext = NULL;
}
Nodeelement *pPrev;
Nodeelement *pNext;
T data;
};
然后是我的迭代课:
template<typename T>
class Iterator
{
public:
Nodeelement<T> *itr;
Iterator(void) : itr(NULL) {}
Iterator(Nodeelement<T>* le) : itr(le) {}
void operator=(Nodeelement<T>* le)
{
itr = le;
}
bool operator!=(Nodeelement<T>* le)
{
if (NULL != itr && itr != le)
return true;
else
return false;
}
void operator++()
{
if (itr != NULL)
itr = itr->pNext;
}
void operator--()
{
if (itr != NULL)
itr = itr->pPrev;
}
T& getData(void)
{
return itr->data;
}
};
然后我的Node类:
template<typename T>
class Node
{
private:
Nodeelement<T>* pFirst;
Nodeelement<T>* pLast;
public:
Node<T>::Node(void) { pFirst = pLast = NULL;}
Node<T>::~Node() { removeEntry(); }
void Node<T>::addEntry(T data)
{
Nodeelement<T> *newNodeElement = new Nodeelement<T>(data);
if (isEmpty())
pLast = pFirst = newNodeElement;
else
{
pLast->pNext = newNodeElement;
newNodeElement->pPrev = pLast;
pLast = newNodeElement;
}
}
bool isEmpty(void) { return (pFirst == NULL) ? true : false; }
void removeEntry(void)
{
if (isEmpty())
return;
while (pFirst->pNext != NULL)
{
Nodeelement<T> *pNow = pLast->pPrev;
pNow->pNext = NULL;
delete pLast;
pLast = pNow;
}
delete pFirst;
pFirst = NULL;
};
void removeEntry(Iterator<T>& it)
{
if (pFirst->pNext == NULL)
{
delete pFirst;
pFirst = pNext = NULL;
}
else if (it == pFirst)
{
pFirst = pFirst->pNext;
delete pFirst->pPrev;
pFirst->pPrev = NULL;
}
else if (it == pLast)
{
pLast = pLast->pPrev;
delete pLast->pNext;
pLast->pNext = NULL;
}
else
{
it.itr->pPrev->pNext = it.itr->pNext;
it.iter->pNext->pPrev = it.iter->pPrev;
delete it.itr;
}
};
Nodeelement<T>* start(void) { return pFirst; }
Nodeelement<T>* postpLast(void)
{
if (pLast == NULL)
return NULL;
else
return pLast->pNext;
}
};
和main.cpp文件:
#include "Node.h"
#include <string>
#include <conio.h>
struct Films
{
std::string titel;
unsigned int year;
int genre;
};
void main(void)
{
Films film, film1, film2;
film.titel = "Stargate";
film.year = 2005;
film.genre = 1;
film1.titel = "V";
film1.year = 2009;
film1.genre = 1;
film2.titel = "Avatar";
film2.year = 2009;
film2.genre = 2;
Node<Films> films;
films.addEntry(film);
films.addEntry(film1);
films.addEntry(film2);
Iterator<Films> itr;
for (itr = films.start(); itr != films.postpLast(); itr++)
{
std::cout << "Film: " << itr.getData().titel.c_str() << std::endl;
}
_getch();
}
(数据只是用于可视化目的的虚拟数据)
我可以添加一个方法来处理递增/递减,但重载递增运算符对我来说看起来更干净(更合乎逻辑)
我希望我的问题很清楚