我很难理解为什么不编译此代码。我将堆栈实现为双链表。我无法让我的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;
    }
}

最佳答案

在下面,您有一个构造函数的声明。这是一个承诺,您将在某处定义一个构造函数。

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


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

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

09-09 23:10