为什么创建友元类的实例会导致"undefined reference to"错误?



我很难理解为什么不编译这段代码。我正在将堆栈实现为双链表。我无法使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资源。我只是不知道为什么会发生在这里。

这是骗子。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)
{
}

因为您还没有在任何地方定义CharNode::CharNode()

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

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

相关内容

最新更新