未定义的引用`class :: class()错误

时间:2016-09-29 00:24:38

标签: c++ file class

我看过其他类似的问题,但我并没有真正理解答案。我收到了这个错误:

在函数main': C:/Users/Danny/ClionProjects/LinkedList/main.cpp:9: undefined reference to linkList :: linkList()' collect2.exe:错误:ld返回1退出状态

linkList.cpp:

#include <iostream>
#include <cstdlib>
#include "linkList.h"

using namespace std;

linkList::linkList()
{
    head = NULL;
    follow = NULL;
    trail = NULL;
}

void linkList::addNode(int dataAdd) 
{
    nodePtr n = new node; 
    n->next = NULL;
    n->data = dataAdd;

    if (head != NULL)
    {
        follow = head;
        while (follow->next != NULL)
        {
            follow = follow->next;
        }
    }
    else
    {
        head = n;
    }

}

void linkList::deleteNode(int nodeDel)
{
    nodePtr delPtr = NULL;
    follow = head;
    trail = head;

    while(follow != NULL)
    {
        trail = follow;
        follow = follow->next;
        if (follow->data == nodeDel)
        {
            delPtr = follow;
            follow = follow->next;
            trail->next = follow;
            delete delPtr;
        }
        if(follow == NULL)
        {
            cout << delPtr << " was not in list\n";
            delete delPtr; // since we did not use delPtr we want to delete it to make sure it doesnt take up memory
        }

    }

}

void linkList::printList()
{
    follow = head;
    while(follow != NULL)
    {
        cout << follow->data << endl;
        follow = follow->next;
    }


}

LinkList.h:

struct node {
    int data;
    node* next;
};

typedef struct node* nodePtr; 


class linkList
{ // the linkList will be composed of nodes

private:
    nodePtr head;
    nodePtr follow;
    nodePtr trail;

public:
    linkList();
    void addNode(int dataAdd);
    void deleteNode(int dataDel);
    void printList();
};

main.cpp中:

#include <cstdlib>
#include "linkList.h"


using namespace std;

int main() {

    linkList myList;


    return 0;
}

我理解它与我的文件链接的方式有关,当我将#include linkList.h更改为#include linkList.cpp在我的主文件中它工作正常为什么会这样?我有另一个类似的程序,它是一个完美的二元搜索树,并具有基本相同的设置类型。所以我的问题是如何解决它?为什么会这样?

1 个答案:

答案 0 :(得分:2)

如果您正在使用自动执行此操作的构建系统/ IDE,则需要将linkList.cpp添加到项目中。你需要:

  1. 使用g++ -c linkList.cpp -o linkList.o
  2. 单独编译
  3. 然后编译并链接最终的可执行文件g++ main.cpp linkList.o
  4. 或直接编译它们(对于较大的项目不可行):g++ main.cpp linkList.cpp

    包含.cpp文件是一个坏主意,您不应该这样做。

相关问题