Проблемы с подключением двух файлов C ++ (List.cc и Queue.cc)

0

Я должен написать Очередь в C++, используя файл списка, который я создал ранее, и у меня есть грубое время, чтобы все было скомпилировано.

Проблема, с которой я в настоящее время сталкиваюсь, заключается в том, что при компиляции я получаю ошибку: Queue.h: 7: 2: error: "List" не называет тип

Как правильно подключить мой файл очереди и файл списка?

Вот файлы, которые я использую: List.h

//an item in the list
  struct ListNode {
  int _value;
  ListNode * _next;
};

class List {
public:
  //Head of list
  ListNode * _head;

  int remove_front();
  void insertSorted( int val );
  void append (int val);
  void prepend (int val);  
  int lookup( int _value );
  int remove( int val );
  void print();
  List();
  ~List();
};

List.cc

//
// Implement the List class
//

#include <stdio.h>
#include "List.h"

ListNode * _head = new ListNode();

//remove the first node in the list
int
List::remove_front(){
    int ret;
    if(_head == 0){
        return -1;
    }
    ret = _head->_value;
    ListNode *temp = new ListNode();
    temp = _head->_next;
    delete(_head);
    _head = temp;
    return ret;
}

//
// Inserts a new element with value "val" in
// ascending order.
//
void
List::insertSorted( int val ){

    ListNode* new_node = new ListNode();
    new_node->_value = val;
    ListNode* current = new ListNode();

    if(_head == 0){
        _head = new_node;
    }else{
        current = _head;
        ListNode* prev = 0;

        while(current != 0){
            if(new_node->_value > current->_value){
                prev = current;
                current = current->_next;
            }else{
                break;
            }
        }
        if(current == _head){
            new_node->_next = _head;    
            _head = new_node;
        }else{
            new_node->_next = current;
            prev->_next = new_node;
        }

    }
}

//
// Inserts a new element with value "val" at
// the end of the list.
//
void
List::append( int val ){

    //create a new node to hold the given value
    ListNode *new_node = new ListNode();        
    new_node->_value = val;

    //if the list is empty
    if(_head == 0){
        //set the new node to be the head
        _head = new_node;
        return ;
    }

    //create a node pointer to the current position (starting at the head)
    ListNode *current = new ListNode();
    current = _head;

    //Loop through the list until we find the end
    while(current->_next != NULL){
        current = current->_next;
    }

    current->_next = new_node;
}

//
// Inserts a new element with value "val" at
// the beginning of the list.
//
void
List::prepend( int val ){
    ListNode *new_node = new ListNode;
    new_node->_value = val;

    if(_head == 0){
        _head = new_node;
        return ;
    }

    ListNode *temp = new ListNode;
    temp = _head;


    _head = new_node;
    _head->_next = temp;
}

// Removes an element with value "val" from List
// Returns 0 if succeeds or -1 if it fails
int 
List:: remove( int val ){

    if(_head == 0){
        printf("List is already empty.\n");
        return -1;
    }

    ListNode *current = new ListNode();
    ListNode* prev = new ListNode();
    current = _head;

    while(current != 0){
        if(current->_value == val){
            if(current == _head){
                _head = _head->_next;
                delete(current);
                return 0;
            }else{
                prev->_next = current->_next;
                delete(current);
                return 0;
            }
        }else{
            prev = current;
            current = current->_next;
        }
    }
    return -1;
}

// Prints The elements in the list. 
void
List::print(){
    ListNode* current = new ListNode();
    while(current != 0){
        printf("%d\n", current->_value);
        current = current->_next;
    }
}

//
// Returns 0 if "value" is in the list or -1 otherwise.
//
int
List::lookup(int val){
    ListNode * current = new ListNode();
    current = _head;
    while(current != NULL){
        if(current->_value == val){
            return 0;
        }
        else{
            current = current->_next;
        }
    }
    return -1;
}

//
// List constructor
//
List::List(){

}

//
// List destructor: delete all list elements, if any.
//
List::~List(){
    ListNode* current = _head;
    while(current != NULL){
        ListNode* next = current->_next;
        delete current;
        current = next;
    } 
}

Queue.h

#ifndef LIST_H
#define LIST_H

class Queue {
public:

    List* queue_list;
    void enqueue(int val);
    int dequeue();

    Queue();
    ~Queue();
};

#endif

Queue.cc

#include <stdio.h>
#include "List.h"
#include "Queue.h"

List *queue_list = new List();

void
Queue::enqueue(int val){
    this->queue_list->prepend(val);
}

int
Queue::dequeue(){
    int value = this->queue_list->remove_front();
    return value;
}

Queue::Queue(){
    //do nothing
}

Queue::~Queue(){
}

queue_main.cc

#include <stdio.h>

#include "Queue.h"
#include "List.h"

Queue *queue;

int main(){
}

Спасибо за помощь!

Теги:

1 ответ

3

Компилятор сообщает вам, что неправильно:

Queue.h: 7: 2: ошибка: "Список" не называет тип

При чтении Queue.h компилятор не может знать, что такое List, поскольку в этом файле нет ничего, что его определяло.

Вам просто нужно добавить форвардное объявление:

#ifndef LIST_H
#define LIST_H

class List; // this is a forward declaration.

class Queue {
public:

    List* queue_list;
    void enqueue(int val);
    int dequeue();

    Queue();
    ~Queue();
};

#endif

В качестве альтернативы (но не обязательно здесь) вы можете просто #include List.h Эмпирическое правило: используйте, если возможно, форвардное объявление. Если компилятор жалуется на это, замените его соответствующим include. include необходимо только в том случае, если компилятор должен знать размер класса/структуры.

  • 0
    Это не точное правило. Вам нужно включить List.h только в List.h случае, если компилятору нужно знать размер рассматриваемого типа, например, если это переменная-член. Если вы используете его в качестве параметра, предполагая, что нет неявных преобразований, вы можете просто использовать предварительное объявление.
  • 0
    Это имеет смысл. Спасибо за помощь!
Показать ещё 1 комментарий

Ещё вопросы

Сообщество Overcoder
Наверх
Меню