试图创建我的类c++的新对象时链接错误

Linking error when trying to create new object of my class C++

本文关键字:对象 错误 链接 新对象 创建 我的 c++      更新时间:2023-10-16

我试图通过创建SingleLinkedList的对象SingleLinkedList m1;来测试我的程序。如果我不创建和操作对象,它会编译得很好。下面是我的main:

int main()
{
    SingleLinkedList m1;
    displayMenu();
    int user_menu;
    cin >> user_menu;   //get input from user which pocket they want to go to 
    while (user_menu != 4)  
    {
        displayChoices();
        int user_input; //
        cin >> user_input;
        if (user_input == 1) {
            cout << "You selected the Pocket Of Magic!" << endl;
            cout << "What do you choose to do?" << endl;
            //string user_choice;
            //cin >> user_choice;
            //SingleLinkedList m1;
            m1.operationMagic();    
        }
        else if (user_input == 2) {
            cout << "You selected the Pocket Of Potions!" << endl;
            cout << "What do you choose to do?" << endl;
        }
    user_input = 4;
    }
    displayMenu();

但是,当我尝试链接时,得到这个错误:

    Undefined symbols for architecture x86_64:
  "SingleLinkedList::SingleLinkedList()", referenced from:
      _main in pocketmaindriver-df9a60.o
  "SingleLinkedList::~SingleLinkedList()", referenced from:
      _main in pocketmaindriver-df9a60.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

这是什么原因?我试着包括。cpp文件,也没有工作。下面是我的。h文件比较:

#ifndef POCKET_OF_MAGIC_
#define POCKET_OF_MAGIC_
//using namespace std;

class SingleNode {
private:
    std::string value;
    SingleNode *nextNode;
public:
    SingleNode();
    SingleNode(std::string s); 
    std::string getValue(); 
    SingleNode* getNextNode(); 
    void setNextNode(SingleNode *newNode); 
};

class SingleLinkedList {
private:
    SingleNode *head;
    SingleNode *tail;
    int totalNodes;
    int itemCount;
public:
    SingleLinkedList();
    ~SingleLinkedList();
    void traverseAndPrint();
    void addNode(std::string data);
    bool deleteNode(std::string data);
    void operationMagic();
}; //end pocket of magic
#endif //end pocket of magic

您没有告诉编译器您的类的。cpp文件。你需要输入g++ PocketOfMagic.cpp pocketmaindriver.cpp -o my_program