c++ - 使用嵌套类的链表?

标签 c++ linked-list

我有类 Agency,它有一个私有(private)嵌套类 Node,应该用于构建 Client 对象的链表。

为了添加一个节点,我需要使用一个重载的 += 运算符来接收一个 Client 对象。 当我想添加第一个对象时:该函数调用 Node 类的 setHead 成员。

但是一旦我尝试修改 head 的数据成员:data 指向接收到的 Client 对象和 nextNULL 发生运行时错误。

我不知道出了什么问题,Client 对象按应有的方式传递(我检查过)- 我认为我在 setHead 的声明中遗漏了一些东西 的参数。

如有任何建议,我们将不胜感激。 顺便说一句,我必须按原样使用现有的私有(private)成员,并且 setHead 方法必须接收指向 Client 的指针。

机构.h

class Agency
{
    public:
        Agency(); //ctor
        Agency& operator+=(const Client&); //overloaded += operator
        ~Agency(); //dtor
    private:
        class Node //node as nested class
        {
            public:
            Node(); //ctor
            void setHead(Client*&); //set head node
            private:
            Client* data; //points to Client
            Node* next; //points to next node on the list
        };

        Node *head; //points to head node of database
};

Agency.cpp相关方法

void Agency::Node::setHead(Client*& temp)
{
    data = temp;
    next = NULL;
}
Agency& Agency::operator+=(const Client& client_add)
{   
    Client* temp = new Client (client_add); //new client object is created using clients copy ctor
    if (!head) //if the head node is NULL
    {
        head->setHead(temp); //assign head node to point to the new client object 
    }
        return *this;
}

编辑: 感谢您的回复,我还有一个问题:

我想要一个 Node 的方法,它将返回一个指向 Node 的指针,这里是声明:

    `Node* nextNode(Node*);` 

功能:

    `Node* MatchmakingAgency::Node::nextNode(Node* start)`

导致编译错误:'Node' does not name a type

如何正确声明这样的方法?

最佳答案

在这段代码中:

if (!head) //in the head node is empty
    {
        head->setHead(temp);

head 不是“空的”。这是一个空指针。然后取消引用导致未定义行为的空指针。

也许你想拥有这个:

head = new Node();

setHead 之前。

关于c++ - 使用嵌套类的链表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25422614/

相关文章:

c - C中的单链表

c++ - 在 FreeRTOS 中使用 LinkedList 保存值失败

c# - Microsoft 标准计算器中使用的变量类型

c++ - 转义特殊字符

c++ - 如何以类似的方式处理不同的模板?

c++ - 线程中的 Select() 系统调用?

c++ - 结构节点与 std::list< >

java - 使用 JNA 从 java 中的内部源对象 (.so) 文件调用 C++ 函数时出现链接异常。

c - 我的 C 代码中出现未知的 "delete"错误

C++:在链表中查找类的最大值