【问题标题】:undefined reference to `class::class() error [duplicate]对`class::class() 错误的未定义引用[重复]
【发布时间】:2016-09-29 00:24:37
【问题描述】:

我看过其他类似的问题,但我并没有很好地理解答案。我收到此错误:

在函数main': C:/Users/Danny/ClionProjects/LinkedList/main.cpp:9: undefined reference tolinkList::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();
};

ma​​in.cpp:

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


using namespace std;

int main() {

    linkList myList;


    return 0;
}

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

【问题讨论】:

    标签: c++ file class


    【解决方案1】:

    如果您使用的是自动生成系统/IDE,则需要将linkList.cpp 添加到您的项目中。您需要:

    1. g++ -c linkList.cpp -o linkList.o单独编译
    2. 然后编译链接最终的可执行文件g++ main.cpp linkList.o

    或直接编译它们(对于大型项目不可行):g++ main.cpp linkList.cpp

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

    【讨论】:

    • 或者,因为 collect2.exe 暗示 CygWin,如果他使用命令行,g++ main.cpp linkList.cpp
    • 啊。我确定这是一个 MS 名称,因为 .exe 谢谢。
    • 你这是什么意思?我正在使用 CLion 来运行程序。 @Ken Y-N
    • @djdangerousdick See this, please.
    猜你喜欢
    • 1970-01-01
    • 2012-09-16
    • 2013-03-20
    • 1970-01-01
    • 2011-03-31
    • 1970-01-01
    • 2013-11-08
    • 2013-01-19
    • 2012-07-29
    相关资源
    最近更新 更多