【问题标题】:Adding object to Linked List error [C++]将对象添加到链接列表错误 [C++]
【发布时间】:2016-02-24 04:20:19
【问题描述】:

我正在尝试将对象添加到链接列表结构,但在 Visual Studio 2015 中不断收到此错误:

Error   LNK2019 unresolved external symbol "public: void __thiscall Stack::add(class Creature *)" (?add@Stack@@QAEXPAVCreature@@@Z) referenced in function _main    

这是我要添加到列表中的代码 - 如果我将其修改为简单地将整数值添加到链接列表(不允许使用 STL),则此功能正常:

#include "Creature.h"

void Stack::add(Creature* obj) {
    /* create head node if list is empty */
    if (head == NULL) {
        head = new Node;
        head->data = obj;
        head->next = NULL;
    }
    else {
        /* set pointer to head */
        Node* temp = head;

        /* iterate until next node is empty */
        while (temp->next != NULL)
            temp = temp->next;

        /* create new node when NULL */
        temp->next = new Node;
        temp->next->data = obj;
        temp->next->next = NULL;
    }
}

这是我的 Creature 类定义(抽象类):

class Creature {
    protected:
        int strike, defense,
            armor, strength,
            damage;
        bool alive;
        string type;
    public:
        Creature(
                strike = 0;
                defense = 0;
                armor = 0;
                strength = 0;
                alive = true;
                type = " ";
                );
        virtual int attack() = 0;
        virtual bool defend(int) = 0;
        virtual string name() = 0;
};

这是我尝试将对象添加到列表的主要功能:

#include "Stack.h"
#include "Creature.h"
#include "Barbarian.h"

int main() {
    Stack q;
    Creature *test = new Barbarian;
    q.add(test);
    return 0;
}

我对 C++ 还很陌生,所以我正在努力学习我能做到的一切,并在寻求帮助之前先尝试自己解决问题,但我只是看不出我在这里可能缺少什么。任何帮助/资源将不胜感激!

【问题讨论】:

  • 你是如何编译你的代码的?
  • @BillLynch 在 Visual Studio 中,我只是转到顶部的“构建”选项卡并选择构建解决方案...这是您的意思吗?
  • 您收到的错误表明您没有正确地将所有源文件包含在二进制文件中。也许视觉工作室有它所采取的行动的日志?

标签: c++ class data-structures linked-list


【解决方案1】:

错误LNK 2019 是因为“声明了函数或变量但未定义”。但是正如您在上面提到的,您已经定义了 stack::add 定义。然后它可能不会添加到您当前的项目中,因此它不会找到定义。

在 Visual Studio 解决方案树中右键单击项目然后添加 -> 现有项目 -> 选择源文件(我猜你的情况是 stack.cpp)

【讨论】:

    【解决方案2】:

    看来我解决了,我继续硬着头皮删除项目并重新导入文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-05
      • 2015-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多