我想解决在主函数中,dList.add()函数处直接传入字面值,而不是定义变量再传入,比如直接传入3,就会出现字面值不能赋值给引用的问题,,该如何修改,以及为什么。。。。
现在如果传入字面值将报错
// 使用类模板,实现双向链表
#include <iostream>
using namespace std;
template<typename T>
struct Node {
Node(T& d):c(d), next(0), pref(0){}
T c;
Node *next, *pref;
}; //---------------------------
template<typename T>
class List{
Node<T> *first, *last;
public:
List();
void add(T& c); //添加元素
void remove(T& c); // 删除指定元素
Node<T>* find(T& c); // 查找元素
void print(); //打印链表
~List(); //析构
};//---------------------
template<typename T>
List<T>::List():first(0), last(0){}
//--------------------------
template<typename T>
void List<T>::add(T& n){
Node<T>* p = new Node<T>(n);
p->next = first; first = p;
(last ? p->next->pref : last) = p;
} //------------------------
template<typename T>
void List<T>::remove(T& n){
Node<T> * p;
if(!(p = find(n))) return ;
(p->next ? p->next->pref : last) = p->pref;
(p->pref ? p->pref->next : first) = p->next;
delete p;
}
template<typename T>
Node<T>* List<T>::find(T& n){
for(Node<T>* p=first; p; p=p->next)
if(p->c==n) return p;
return 0;
}//--------------------------
template<typename T>
List<T>::~List(){
for(Node<T>* p; p = first; delete p)
first = first -> next;
}//-----------------------------
template<typename T>
void List<T>::print(){
for(Node<T>* p = first; p; p = p->next)
cout << p->c << " ";
cout << endl;
}
int main()
{
List<double> dList;
double a = 3;
double b = 4;
double c= 5;
dList.add(a);
dList.add(b);
dList.add(c);
dList.print();
dList.remove(a);
dList.print();
return 0;
}