C++链接器因符号而失败

C++ Linker failure because of symbol

本文关键字:失败 符号 链接 C++      更新时间:2023-10-16

我正在写一些C++代码,请注意,我是该语言的新手。我已经解决了用G++编译时的所有错误,但我似乎不明白为什么我会出现链接失败。

我已经附上了我的代码和错误:

错误:

$ g++ -std=c++11 algorithm.cpp 
Undefined symbols for architecture x86_64:
  "Graph::Graph()", referenced from:
      _main in algorithm-14102f.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

我的文件(目前不完整):

#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <cstdlib>
#include <map>
using namespace std;
class Graph {
    struct node {  // nodes that you read
       string name;
       int id;            // index of the node in the nodes vector
       vector<int> in;    // parent(s) that can lead to this node
       vector<int> out;   // children you can go to
        node(string key, int ind, vector<int> *in = new vector<int>(), vector<int> *out = new vector<int>()) : 
            name(key), id(ind) {}
    };
    vector<node> nodes;    // all the nodes in arbitrary sequential order
    map <string, int> dict; // map converting the names into ids
    public:
        Graph(); // class constructor
    void addNode(string key, int id){
        node *item = new node(key, id);
    }
    int getNodesLength(){
        return nodes.size();
    }
};
int main()
{
    Graph * graph = new Graph();
    std::string s;
    std::string word;
    while(std::getline(std::cin, s)) {
        for(char c : s) {
            if (c == ' '){ // right side words
                graph->addNode(word, graph->getNodesLength());

                word = "";
            } else if (c == ':') { // left side word
                graph->addNode(word, graph->getNodesLength());

                word = "";
            } else { // letter char
                word += c;  //  
            }
        }
    }
    return 0;
}

这意味着您没有实现Graph类的构造函数。要么不要在头中声明它(这样编译器就会为你生成一个默认的构造函数),要么如果你声明了,就实现它

Graph * graph = new Graph(); Graph已经位于顶级命名空间中。

您还忘记提供constructor

相关文章: