2017-01-18 5 views
1

Я пытаюсь создать LinkedList, который берет информацию о пользователе и сохраняет ее в своих узлах. После этого будет отображаться информация пользователя. Я уже работал корыто это и это то, что у меня есть:C++ Simple LinkedList из переменных области

#include <iostream> 
    using namespace std; 

    template <typename T> 
    class Node 
    { 
    T data; 
    Node* next; 
}; 

template <typename T> 
class LinkedList 

{ 
    public: 
    //Default constructor 
    LinkedList(){ 
     head = NULL; 
     tail = NULL; 
    } 

    void addData(T val){ 
     Node* newNode = new Node; 
     newNode->data = val; 
     newNode->next = NULL; // we add newNode at end of linked list 
     if(head == NULL){ 
      head = newNode; 
      tail = newNode; 
     } 

     else{ 
      tail ->next = newNode; 
      tail = newNode; 
     } 
    } 

    void printData() { 
     for(Node* i = head; i!=NULL; i = i -> next){ 
      cout << i->data << " " ; 

     } 
    } 

    private: 
    //Declare the head and tail of the LinkedList 
     Node* head; 
     Node* tail; 

}; 

int main(){ 

    LinkedList<string> usrInput; 
    cout << "Enter a number or word : "; 
    string input ; 
    cin >> input; 

    usrInput.addData(input); 
    usrInput.printData(); 



    LinkedList<int> numbers; 
    while (true) 
    { 
     cout<< "Enter a number (-1 to stop): "; 
     int num; 
     cin >> num; 

     if (num == -1) 
      break; 

     numbers.addData(num); 
    } 
    numbers.printData(); 


} 

Проблема заключается в том, что, когда я скомпилировать свою программу, я получаю кучу ошибок, относящиеся к из переменных-членов сферы. Являются ли переменные-члены не частными?


Это то, что у меня есть для отладчика:

46:9: error: invalid use of template-name 'Node' without an argument list 

47:9: error: invalid use of template-name 'Node' without an argument list 

In constructor 'LinkedList<T>::LinkedList()': 

18:9: error: 'head' was not declared in this scope 

19:9: error: 'tail' was not declared in this scope 

In member function 'void LinkedList<T>::addData(T)': 

23:13: error: missing template arguments before '*' token 

23:15: error: 'newNode' was not declared in this scope 

23:29: error: invalid use of template-name 'Node' without an argument list 

26:13: error: 'head' was not declared in this scope 

28:13: error: 'tail' was not declared in this scope 

32:13: error: 'tail' was not declared in this scope 

In member function 'void LinkedList<T>::printData()': 

38:17: error: missing template arguments before '*' token 

38:19: error: 'i' was not declared in this scope 

38:23: error: 'head' was not declared in this scope 
+0

'Node * головка;' – greatwolf

ответ

3

Элементы данных класса являются закрытыми по умолчанию. Они по умолчанию публикуются в структурах. То есть в:

class Node 
    { 
    T data; 
    Node* next; 
}; 

Класс LinkedList не имеет видимости для членов узла. Попробуйте либо с помощью:

struct Node { 
    T data; 
    Node* next; 
}; 

или

class Node { 
    public: 
     T data; 
     Node* next; 
}; 

Стилистически, наиболее реальной реализации гнездятся узел в качестве частного члена структуры внутри класса LinkedList.

+0

Спасибо! Не является родным разработчиком C++. Тот же пирог просто отличается вкусом. Это решило мою проблему. –

+0

N.P. рассмотрите вопрос о том, как ответить на вопрос для будущих людей. – tegtmeye

+0

Уважаемый tegtmeye, как я могу поставить вопрос на вопрос? Я новичок здесь: D. Я также должен отметить еще один мой вопрос, касающийся asyncTask, поэтому, пожалуйста, дайте мне знать. –

1

Node в одиночку не относится к действительному типу в вашем коде. Вы должны использовать Node<T>.

Когда компилятор встречается с Node, он помещает его как незаконное использование и отбрасывает переменную или член, определенные этим типом, вызывая дополнительные ошибки позже в компиляции при использовании переменной или члена.

После того, как вы переключитесь на использование полного типа с помощью Node<T>, вы столкнетесь с проблемой, упомянутой в другом ответе, с частным членством членов класса Node<T>.

+0

Thankyou я решил тип несоответствие аргумент линии 46 и 47 уже. –

+0

Теперь мой вопрос заключается в моем диапазоне переменных. Почему они не входят в сферу охвата. –

+0

@ErickRamirez Вы заменили все виды использования узла с узлом ? –

0

я надеюсь, что мой ответ будет helpull для других людей тоже, даже если я поздно ха-ха :):

#include <iostream> 
    using namespace std; 

template <typename Type> 
class Node 
{  
    template<typename T> friend class LinkedList;/* you need to make your linkedList 
     class a friend variable to be able to,acces the private members directly from the objects inside the class Linkedlist. 
     other option its to make them public, but it is not recomended and other option si to make functions to acces de data, but this will be very messy, just make your linkedlist class friend*/ 
    Type data; 
    Node<Type>* next; // you need to specify which data type the node will be 
}; 

template <typename T> 
class LinkedList 
{ 
public: 
//Default constructor 
LinkedList(){ 
    head = NULL; 
    tail = NULL; 
} 

void addData(T val){ 
    // you can't forget to specify the data type since it is a template!! 
    Node<T>* newNode = new Node<T>(); 
    newNode->data = val; 
    newNode->next = NULL; // we add newNode at end of linked list 
    if(head == NULL){ 
     head = newNode; 
     tail = newNode; 
    } 

    else{ 
     tail ->next = newNode; 
     tail = newNode; 
    } 
} 

void printData() { 
    // again specify the data type of the template 
    for(Node<T>* i = head; i !=NULL; i = i -> next){ 
     cout << i->data << "\n" ; 

    } 
} 

private: 
    //Declare the head and tail of the LinkedList 
    Node<T>* head;// Again specify the data type of the template 
    Node<T>* tail;// here the same thing 

}; 

int main(){ 

    LinkedList<string> usrInput; 
    cout << "Enter a number or word : "; 
    string input ; 
    getline(cin,input);// use the get line function to get strings from standar input 

    usrInput.addData(input); 
    usrInput.printData(); 

    // Declare the num variable otuside and initialize it, you should always initialize the variables 
    int num(0); 
    LinkedList<int> numbers; 
    while (true) 
    { 
     cout<< "Enter a number (-1 to stop): "; 
     // you need to validate the input if you don't want to run an infinite loop 
     if(!(cin >> num)){ 
      cin.clear(); 
      cin.ignore(100,'\n'); 
     } 
     else { 
     // if we succes with the imput you can add the data to the linked list :) 
      if (num == -1){break;} 
      numbers.addData(num); 
     } 
    } 
     numbers.printData(); 


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