2013-02-28 4 views
0

Вот быстрый шаблон объекта Dequeue, который я создал, и он отлично работал на терминале Mac, но визуальный C++ не будет работать для меня. Извините заранее, если это глупый вопрос, я немного новичок в C++ и шаблонах. Вот код:Visual C++ не позволит мне использовать шаблон?

#include <iostream> 
using namespace std; 

template <typename T> 
class Dequeue; 

template <typename T> 
class node; 

template <typename T> 
ostream& operator<<(ostream&, const Dequeue<T>&); 

template <typename T> 
class node{ 
public: 
    node<T>* next; 
    node<T>* prev; 
    T data; 
    node(T data=T(), node<T>* next=NULL, node<T>* prev=NULL); 
}; 

template <typename T> 
node<T>::node(T _data, node<T>* _next, node<T>* _prev){ 
    data = _data; 
    next = _next; 
    prev = _prev; 
} 

template <typename T> 
class Dequeue{ 
private: 
    node<T>* head; 
    node<T>* tail; 
    int _size; 
    void clear(); 
public: 
    Dequeue(); 
    ~Dequeue(); 
    Dequeue(const Dequeue<T>&); 
    const Dequeue<T>& operator=(const Dequeue<T>&); 
    friend ostream& operator<< <>(ostream&, Dequeue<T>&); 
    void push_front(T&); 
    void push_back(T&); 
    void pop_front(); 
    void pop_back(); 
    T front(); 
    T back(); 
    int size(); 
    bool isEmpty(); 
}; 

template <typename T> 
Dequeue<T>::Dequeue(){ 
    _size = 0; 
    head = NULL; 
    tail = NULL; 
} 

template <typename T> 
Dequeue<T>::~Dequeue(){ 
    clear(); 
} 

template <typename T> 
void Dequeue<T>::clear(){ 
    while(_size > 0) 
     pop_front(); 
} 

template <typename T> 
Dequeue<T>::Dequeue(const Dequeue<T>& other){ 
    head = NULL; 
    tail = NULL; 
    _size = 0; 

    *this = other; 
} 

template <typename T> 
const Dequeue<T>& Dequeue<T>::operator=(const Dequeue<T>& other){ 
    if(this = &other) 
     return *this; 
    clear(); 
    node<T>* np = other.head; 
    while(np!=NULL){ 
     node<T>* p = new node<T>(np->data); 

     if(head == tail == NULL) 
      head = tail = p; 

     else{ 
      tail->next = p; 
      p->prev = tail; 
     } 

     tail = p; 
     np = np->next; 
    } 

    _size = other._size; 
    return *this; 
} 

template <typename T> 
ostream& operator<<(ostream& out_str, Dequeue<T>& other){ 
    node<T>* np = other.head; 

    while(np != NULL){ 
     out_str << np->data << endl; 
     np = np->next; 
    } 
    return out_str; 
} 

template <typename T> 
void Dequeue<T>::push_front(T& object){ 
    node<T>* np = new node<T>(object); 

    np->next = head; 
    head->prev = np; 
    head = np; 

    _size++; 
} 

template <typename T> 
void Dequeue<T>::push_back(T& object){ 
    node<T>* np = new node<T>(object); 

    tail->next = np; 
    np->prev = tail; 
    tail = np; 

    _size++; 
} 

template <typename T> 
void Dequeue<T>::pop_front(){ 
    node<T>* np = head; 
    head = head->next; 
    delete np; 
    head->prev=NULL; 

    _size--; 
} 

template <typename T> 
void Dequeue<T>::pop_back(){ 
    node<T>* np = tail; 
    tail = np->prev; 
    delete np; 
    tail->next = NULL; 

    size--; 
} 

template <typename T> 
T Dequeue<T>::front(){ 
    return head->data; 
} 

template <typename T> 
T Dequeue<T>::back(){ 
    return tail->data; 
} 

template <typename T> 
int Dequeue<T>::size(){ 
    return _size; 
} 

template <typename T> 
bool Dequeue<T>::isEmpty(){ 
    if(size == 0) 
     return true; 
    else 
     return false; 
} 

int main(){ 
    Dequeue<int> A; 

    A.push_back(5); 
    A.push_front(6); 
    A.push_back(7); 

    cout << A << endl; 

    cin.get(); 
    return 0; 
} 

А вот ошибки я получаю:

1>------ Build started: Project: Kevin, Configuration: Debug Win32 ------ 
1> Dequeue.cpp 
1>c:\users\kevin nguyen\documents\visual studio 2010\projects\kevin\kevin\dequeue.cpp(184): error C2664: 'Dequeue<T>::push_back' : cannot convert parameter 1 from 'int' to 'int &' 
1>   with 
1>   [ 
1>    T=int 
1>   ] 
1>c:\users\kevin nguyen\documents\visual studio 2010\projects\kevin\kevin\dequeue.cpp(185): error C2664: 'Dequeue<T>::push_front' : cannot convert parameter 1 from 'int' to 'int &' 
1>   with 
1>   [ 
1>    T=int 
1>   ] 
1>c:\users\kevin nguyen\documents\visual studio 2010\projects\kevin\kevin\dequeue.cpp(186): error C2664: 'Dequeue<T>::push_back' : cannot convert parameter 1 from 'int' to 'int &' 
1>   with 
1>   [ 
1>    T=int 
1>   ] 
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ========== 

ответ

0

Ваш вопрос в том, что в ваших заявлениях, вы пытаетесь взять ссылку на T. В этом случае литералы, которые вы передаете в свою функцию (например, A.push_back(5)), не обязательно являются тем, что может быть использовано для ссылки. Ваша декларация должна, скорее всего, выглядеть примерно так:

/* use `const` */ 
void Dequeue<T>::push_front(const T& object) 
/* Same for push_back: use `const` */ 
void Dequeue<T>::push_back(const T& object) 

Const предоставит вам возможность передавать постоянные данные в качестве ссылки. Вы все равно делаете копию, поэтому убедитесь, что все ваши объявления полностью опущены, используя const, если они берут ссылку.

Кроме того, может быть разумно не указывать ваш параметр T data в вашем узле по умолчанию только что созданному T. Это заставит любой тип данных, который вы используете с вашим Linked List, иметь конструктор по умолчанию. Просто возьмите const T& data вместо этого, или нет T.

+0

Спасибо! Сейчас он работает – knguyen2525

Смежные вопросы