2011-03-13 9 views
17

Cuando compilo mi código para una lista vinculada, obtengo un montón de errores de referencia no definidos. El código está abajo. He estado recopilando con estas dos afirmaciones:Indefinido Referencia a

g++ test.cpp 

, así como

g++ LinearNode.h LinearNode.cpp LinkedList.h LinkedList.cpp test.cpp 

Realmente no entiendo por qué estoy recibiendo estos errores porque soy muy oxidado en clases en C++. Realmente podría usar algo de ayuda.

LinearNode.h:

#ifndef LINEARNODE_H 
#define LINEARNODE_H 
#include<iostream> 

using namespace std; 

class LinearNode 
{ 
    public: 
     //Constructor for the LinearNode class that takes no arguments 
     LinearNode(); 
     //Constructor for the LinearNode class that takes the element as an argument 
     LinearNode(int el); 
     //returns the next node in the set. 
     LinearNode* getNext(); 
     //returns the previous node in the set 
     LinearNode* getPrevious(); 
     //sets the next element in the set 
     void setNext(LinearNode* node); 
     //sets the previous element in the set 
     void setPrevious(LinearNode* node); 
     //sets the element of the node 
     void setElement(int el); 
     //gets the element of the node 
     int getElement(); 

    private: 
     LinearNode* next; 
     LinearNode* previous; 
     int element;   
};//ends the LinearNode class 

#endif 

LinearNode.cpp:

#ifndef LINEARNODE_cpp 
#define LINEARNODE_cpp 
#include<iostream> 
#include"LinearNode.h" 

using namespace std; 

//Constructor for LinearNode, sets next and element to initialized states 
LinearNode::LinearNode() 
{ 
    next = NULL; 
    element = 0; 
}//ends LinearNode default constructor 

//Constructor for LinearNode takes an element as argument. 
LinearNode::LinearNode(int el) 
{ 
    next = NULL; 
    previous = NULL; 
    element = 0; 
}//ends LinearNode constructor 

//returns the next element in the structure 
LinearNode* LinearNode::getNext() 
{ 
    return next; 
}//ends getNext function 

//returns previous element in structure 
LinearNode* LinearNode::getPrevious() 
{ 
    return previous; 
}//ends getPrevious function 

//sets the next variable for the node 
void LinearNode::setNext(LinearNode* node) 
{ 
    next = node; 
}//ends the setNext function 

//sets previous for the node 
void LinearNode::setPrevious(LinearNode* node) 
{ 
    previous = node; 
}//ends the setPrevious function 

//returns element of the node 
int LinearNode::getElement() 
{ 
    return element; 
}//ends the getelement function 

//sets the element of the node 
void LinearNode::setElement(int el) 
{ 
    element = el; 
}//ends the setElement function 

#endif 

LinkedList.h:

#ifndef LINKEDLIST_H 
#define LINKEDLIST_H 
#include<iostream> 
#include"LinearNode.h" 

using namespace std; 

class LinkedList 
{ 
    public: 
     LinkedList(); 
     void add(int element); 
     int removie (int element); 

    private: 
     int count; 
     LinearNode *contents; 
};//ends the class linked list 

#endif 

LinkedList.cpp:

#ifndef LINKEDLIST_CPP 
#define LINKEDLIST_CPP 

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

using namespace std; 

//linkedlist constructor for an empty linked list 
LinkedList::LinkedList() 
{ 
    count = 0; 
    contents = NULL; 
}//ends the constructor 

//adds an element to the front of the linked list 
void LinkedList::add(int element) 
{ 
    int found = 0, current = 0; 

    while((found == 0) && (current !=count)) 
    { 
     if (contents.getElement() == element) 
      found = 1; 
     else  
     { 
      contents = contents.getNext(); 
      current++; 
     }//ends the else statement 
    }//ends the while loop 

    if (found == 0) 
    { 
     LinearNode node = new LinearNode(element); 
     node.setNext(contents); 
     contents.setPrevious(node); 
     count++; 
    }//ends the found == 0 if statment 
}//ends the add function 

//this function removes one element from the linked list. 
int LinearNode::remove(int element) 
{ 
    int found = 0; 

    if (count == 0) 
     cout << "The list is empty" << endl; 
    else 
    { 
     if (contents.getElement() == element) 
     { 
      result = contents.getElement(); 
      contents = contents.getNext(); 
     }//ends the contents.getElement() == element 
     else 
     { 
      previous = contents; 
      current = contents.getNext(); 
      for (int index = 0; ((index < count) && (found == 0))index++) 
       if (current.getElement() = element) 
        found = 1; 
       else 
       { 
        previous = current; 
        current = current.getNext(); 
       }//ends the else statement 

      if (found == 0) 
       cout << "The element is not in the list" << endl; 
      else 
      { 
       result = current.getElement(); 
       previous.setNext(current.getNext()); 
      }//ends else statement 

     }//ends the else stamtement 

     count--; 
    }//ends the else statement of count == 0 
    return result; 
}//ends the remove function 

#endif 

test.cpp:

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

using namespace std; 

int main() 
{ 

    LinearNode node1, node2, node3, move; 
    LinkedList list;  

    node1.setElement(1); 
    node2.setElement(2); 
    node3.setElement(3); 
} 
+2

Antes que nada, no coloque los archivos ".h" como un parámetro para el compilador. Ya están incluidos en sus archivos ".cpp". ¿Cuáles son las referencias faltantes? ¿Cuál es el error del enlazador que está obteniendo? – littleadv

+1

Además, * never * put 'using namespace std;' en un archivo .h. –

+0

La próxima vez pegue los mensajes de error también. – karlphillip

Respuesta

13
  1. Por lo general, las cabeceras de los guardias son para los archivos de cabecera (es decir, .h) no para archivos de origen (es decir, .cpp).
  2. Incluya los encabezados y espacios de nombres estándar necesarios en los archivos fuente.

LinearNode.h:

#ifndef LINEARNODE_H 
#define LINEARNODE_H 

class LinearNode 
{ 
    // ..... 
}; 

#endif 

LinearNode.cpp:

#include "LinearNode.h" 
#include <iostream> 
using namespace std; 
// And now the definitions 

LinkedList.h:

#ifndef LINKEDLIST_H 
#define LINKEDLIST_H 

class LinearNode; // Forward Declaration 
class LinkedList 
{ 
    // ... 
}; 

#endif 

LinkedList.cpp

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

// Definitions 

test.cpp es archivo de origen está muy bien. Tenga en cuenta que los archivos de encabezado nunca se compilan. Suponiendo que todos los archivos están en una sola carpeta -

g++ LinearNode.cpp LinkedList.cpp test.cpp -o exe.out 
+0

¡Gracias por la ayuda! Me siento realmente estúpido. Cometí esos errores, ha pasado tanto tiempo desde que hice la programación en C++ – tpar44

+2

@ tpar44 - No hay problema. Incluso yo soy un principiante. E incluso los experimentados pueden cometer errores en 'C++'. Tal es el lenguaje :) – Mahesh

3
g++ test.cpp LinearNode.cpp LinkedList.cpp -o test 
+0

Esto resolverá las dependencias del vinculador que generan errores 'Referencia no definida a'. Pero esto solo funcionará si todos los archivos están en el mismo directorio. – karlphillip

+0

¡Gracias por la ayuda! ¡Eso funciona! – tpar44

+0

No hay problema, amigo. – karlphillip

1

Otra forma de obtener este error es escribiendo accidentalmente la definición de algo en un espacio de nombres en el anonimato:

foo.h:

namespace foo { 
    void bar(); 
} 

foo.cc:

namespace foo { 
    namespace { // wrong 
     void bar() { cout << "hello"; }; 
    } 
} 

otro.archivo de cc:

#include "foo.h" 

void baz() { 
    foo::bar(); 
} 
+0

me ayudó a descubrir qué pasaba con mi prog –