2013-03-19 1 views
0

У меня сложнее всего разобраться в этом. Ошибка в строке 58 main.cpp, я написал заметный комментарий по линии 58.Как объявить объект <template> в C++

|58|error: expected primary-expression before ';' token 

main.cpp

#include <iostream> 
#include <vector> 
#include "LinkedList.h" 
using namespace std; 

bool eic(const string &str1, const string &str2){ 
    if(str1.length() != str2. length()) 
     return false; 
    for(int i = 0; i < str1.length(); i++) 
     if(toupper(str1[i]) != toupper(str2[i])) return false; 
    return true; 
} 

vector<string> tokenizer(const string &str, char delim, bool emptyok) 
{ 
    vector<string> tokens; 
    string t; 

    for(int i = 0; i < str.length(); i++) 
    { 
     if (str[i] == delim) 
     { 
      if(emptyok || (t.length() != 0)) 
       tokens.push_back(t); 

      t.clear(); 
      continue; 
     } 

     t.push_back(str[i]); 
    } 
    if(emptyok || (t.length() != 0)) tokens.push_back(t); 
    return tokens; 
} 

int main(){ 
    LinkedList<int> sList;// = LinkedList<int>; 
    string input; 
    cout << "Type 'commands' to see the list of commands" << endl; 
    cin >> input; 
    vector<string> inputV = tokenizer(input,' ',false); 
    while(!eic(input,"exit")){ 
     if(eic(input,"commands")){ 
      cout << endl; 
      cout << "Do not include <> in any commands" << endl; 
      cout << endl; 
      cout << "Create <name of list>: Create a new list and names it." << endl; 
      cout << "Print <name of list>: Prints out the entire list." << endl; 
      cout << "Add <name of list> <item>: Adds an element to the list." << endl; 
      cout << "Delete <name of list> <item>: Deletes an element from the list." << endl; 
      cout << "DeleteAll <name of list> <item>: Deletes all occurences of the element from the list." << endl; 
      cout << "MakeEmpty <name of list>: Removes all elements from the list." << endl; 
      cout << "Length <name of list>: Tells you how many elements are in the list" << endl; 
      cout << "Remove <name of list> deletes an entire list" << endl; 
      cout << "Exit: Terminates the program" << endl; 
     } 
     else if(eic(inputV[0],"create")){ 
      sList = LinkedList<int>; // LINE 58 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 
      sList.setName(inputV[1]); 
      cout << sList.getName(); 
      //cout << "This function is still under construction" << endl; 
     } 
     else if(eic(inputV[0],"print")){ 
      cout << "This function is still under construction" << endl; 
     } 
     else if(eic(inputV[0],"add")){ 
      //sList->insertItem(9); 
      cout << "This function is still under construction" << endl; 
     } 
     else if(eic(inputV[0],"delete")){ 
      cout << "This function is still under construction" << endl; 
     } 
     else if(eic(inputV[0],"deleteAll")){ 
      cout << "This function is still under construction" << endl; 
     } 
     else if(eic(inputV[0],"makeEmpty")){ 
      cout << "This function is still under construction" << endl; 
     } 
     else if(eic(inputV[0],"length")){ 
      cout << "This function is still under construction" << endl; 
     } 
     else if(eic(inputV[0],"remove")){ 
      cout << "This function is still under construction" << endl; 
     } 
     else cout << endl << "Invalid inquiry, please enter 'commands' to see a list of valid commands." << endl; 
     cin >> input; 
    } 
} 

Если вам это нужно здесь мой LinkedList.cpp файл

#include <iostream> 
#include "LinkedList.h" 

using namespace std; 

template <class xtype> 
LinkedList<xtype>::LinkedList() 
{ 
    cout << "List created successfuly\n"; 
} 

template <class xtype> 
void LinkedList<xtype>::setLength(int x){ 
    length = x; 
} 

template <class xtype> 
int LinkedList<xtype>::getLength(){ 
    return length; 
} 

template <class xtype> 
void LinkedList<xtype>::setName(string x){ 
    name = x; 
} 

template <class xtype> 
string LinkedList<xtype>::getName(){ 
    return name; 
} 

template <class xtype> 
void LinkedList<xtype>::insertItem(xtype item){ 
    node<xtype> *temp = new node<xtype>; 
    if(head == NULL || head->info > item){ 
     temp->next = head; 
     head = temp; 
    } 
    else{ 
     node<xtype> *q = head; 
     node<xtype> *p = head->next; 

     while(p != head && p->info <= item){ 
      q = p; 
      p = p->next; 
     } 
     q->next = temp; 
     temp->next = p; 
    } 
} 

template class LinkedList<int>; 

И заголовочный файл LinkedList

#ifndef LINKEDLIST_H 
#define LINKEDLIST_H 
#include <iostream> 
using namespace std; 

template <class xtype> 
struct node{ 
    xtype info; 
    node *next; 
    node *prev; 
}; 

template <class xtype> 
class LinkedList 
{ 
    public: 
     LinkedList(); 
     int getLength(); 
     void setLength(int); 
     void setName(string); 
     string getName(); 
     //bool searchItem(xtype item); 
     void insertItem(xtype item); 
     //void deleteItem(xtype item); 
     //int numOccur(xtype item); 
    protected: 
    private: 
     node<xtype> *head; 
     node<xtype> *term; 
     int length; 
     string name; 
}; 

#endif // LINKEDLIST_H 

Любая помощь, которую вы можете мне дать, будет очень признательна. Я новичок в C++, исходя из java, и я только что занимался этим всю прошлую ночь до сих пор.

+2

'LinkedList ' это имя типа, а не объект, чтобы создать временный объект этого типа делают 'LinkedList () '. То, что вы написали, эквивалентно 'i = int;' –

+0

Я собираюсь что-то нанести ... Я не могу поверить, что это то, чего я не хватало ...... Мне нужно спать –

+0

Да, но потом я получаю чувствуя, что он намеревается использовать его как «новый LinkedList ()', потому что он уже создал «объект», где он его объявил. @ Антон Ершов, вы новичок в C++? – nonsensickle

ответ

4

Когда вы объявляете sList как LinkedList<int>, вы уже вывели конструктор по умолчанию для инициализации sList. Нет необходимости назначать это явно, как вы (старайтесь) делать в строке сбоя.

Это демонстрирует путаницу, но жизненно важную концепцию при выходе из Java в C++: RAII

+1

Это допустимый способ очистить список, т. Е. Повторно инициализировать его до состояния, построенного по умолчанию. –

+0

Получил это, спасибо, чувак. –

+1

Erm, yes, 'sList = LinkedList ();' очистит объект, предположив, что оператор правильного присваивания –

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