为什么创建朋友类的实例会导致“未定义的引用”错误?

时间:2018-10-30 00:08:34

标签: c++ doubly-linked-list undefined-reference

我很难理解为什么不编译此代码。我将堆栈实现为双链表。我无法让我的AddToHead()工作。更具体地说,如果我尝试动态创建CharNode对象,则该程序将无法编译。我以为拥有#include“ charlist.h”可以使程序访问CharNode类,因为它位于charlist.h

我使用以下命令编译:g ++ -ansi -pedantic -Wall charlist.cxx -o clist

这是我得到的错误:

/tmp/ccHzaOmz.o: In function `CharList::AddToHead(char)':
charlist.cxx:(.text+0xe9): undefined reference to `CharNode::CharNode(char, CharNode*, CharNode*)'
collect2: error: ld returned 1 exit status

我知道未定义的引用意味着链接器无法找到CharNode资源。我只是不知道为什么会在这里发生。

这里是charlist.h

#ifndef __CharList__
#define __CharList__

#include <iostream>
#include <string>

using namespace std;

class CharList;

//CharNode class is clearly here in charlist.h
class CharNode
{
private:
    char value;
    CharNode* prev;
    CharNode* next;
public:
    CharNode(char value, CharNode* prev = NULL, CharNode* next = NULL);
    friend class CharList;
};

class CharList
{
private:
    CharNode* h;
    CharNode* t;
public:
    CharList();
    ~CharList();
    bool IsEmpty() const;
    char GetHead() const; //FUNCTION CAUSING ERROR
    char GetTail() const;
    void AddToHead(char v);
    void AddToTail(char v);
};

#endif //__CharList__

这是charlist.cxx

#include <iostream>
#include <string>
#include <sstream>
#include <cassert>
#include <stdlib.h>
#include "charlist.h"

using namespace std;

CharList::CharList()
{
    h = t = NULL;
}

bool CharList::IsEmpty() const
{
    return (h == NULL);
}
//All other member functions excluded for relevancy 

void CharList::AddToHead(char v){
    CharNode* newHead;
    newHead = new CharNode(v); //Why cant I do this? Error Line.
    newHead->prev = NULL;
    newHead->next = h;

    if (IsEmpty()){
        t = newHead;
        h = newHead;
    } else {
        h->prev = newHead;
        h = newHead;
    }
}

2 个答案:

答案 0 :(得分:2)

下面,您有一个构造函数的声明。这是一个保证,您将定义某个地方的构造函数。

CharNode(char value, CharNode* prev = NULL, CharNode* next = NULL);

将其更改为也包含定义,您将不会得到该未定义错误

CharNode(char value, CharNode* prev = NULL, CharNode* next = NULL)
    : value(value)
    , prev(prev)
    , next(next)
{
}

答案 1 :(得分:0)

因为尚未在任何地方定义CharNode::CharNode()

在charlist.cxx中填写以下内容,它应该建立并链接:

CharNode::CharNode(char value, CharNode* prev = NULL, CharNode* next = NULL)
{
  // Your code here...
}