[间接寻址级别不同]
问题描述:
1、写了一个单链表的模板类
2、取链表中一个节点的值时,出现
错误 1 error C2040: “b”: “double *”与“double”的间接寻址级别不同 f:\work_code\vs2005_code\链表\链表\main.cpp 11
问题出在:突出部分
主函数[main.cpp]:
#include "randy_list.h"
#include <iostream>
using namespace std;
int main()
{
List<double> l;
double a = 2,b = 3;
l.add_node(&a);
l.add_node(&b);
double *b = l.get_node(2);//此句会出现上述问题
l.del_node(1);
l.del_node(1);
l.clear_list();
l.add_node(&a);
std::cout << *(l.get_node(1)) << endl; //此句能顺利通过
return 0;
}
模板类[randy_list.h]:
#ifndef _RANDY_LIST_H_
#define _RANDY_LIST_H_
#include <cstring>
#ifndef NULL
#define NULL 0
#endif
struct Node
{
void *data;
Node *next;
};
template<typename T>
class List
{
public:
List():length(0),phead(NULL),plast(NULL) {};
~List(){ if (phead) clear_list(); };
bool add_node(T *data);
bool del_node(int inode);
T* get_node(int inode);
void clear_list();
protected:
private:
int length;
Node *phead;
Node *plast;
};
template<typename T>
bool List<T>::add_node(T *data)
{
if (!phead)
{
phead = new Node;
phead->data = new T;
if (!phead->data) { delete phead; return false; }
memcpy(phead->data,data,sizeof(T));
plast = phead;
plast->next = NULL;
length++;
}
else
{
plast->next = new Node;
plast->next->data = new T;
if (!plast->next->data) { delete plast->next; return false; }
memcpy(plast->next->data,data,sizeof(T));
plast = plast->next;
plast->next = NULL;
length++;
}
return true;
}
template<typename T>
bool List<T>::del_node(int inode)
{
Node *p = phead,*q = NULL;
if (inode <= 0 || inode > length)
{
return false;
}
if (1 == inode)
{
q = phead;
phead = q->next;
}
else
{
int i = 1;
while (i < inode-1)
{
p = p->next;
i++;
}
q = p->next;
p->next = q->next;
}
delete q->data;
delete q;
length--;
return true;
}
template<typename T>
void List<T>::clear_list()
{
Node *p = NULL;
while (phead)
{
p = phead->next;
delete phead->data;
delete phead;
phead = p;
}
length = 0;
phead = NULL;
plast = NULL;
}
template<typename T>
T* List<T>::get_node(int inode)
{
Node *p = phead;
if (inode <= 0 || inode > length)
{
return NULL; //
}
int i = 0;
while (i < inode-1)
{
p = p->next;
i++;
}
return (T*)p->data;
}
#endif
希望哪位大侠能出来指点下小弟,三个妞!