使用嵌套类的链接列表?

时间:2014-08-21 09:19:50

标签: c++ linked-list

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

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

但是,一旦我尝试修改headdata的数据成员以指向收到的Client对象,并next指向NULL时间错误发生。

我无法弄清楚什么是错的,Client对象按原样传递(我检查过) - 我认为我在setHead的声明中遗漏了一些东西参数。

会感谢任何建议。 顺便说一句,我必须按原样使用现有的私有成员,并且setHead方法必须接收指向Client的指针。

Agency.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

我如何正确宣布这样的方法?

1 个答案:

答案 0 :(得分:2)

在此代码中:

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

head不是"空"。它是一个空指针。然后你取消引用空指针,这会导致未定义的行为。

也许你的意思是:

head = new Node();
setHead之前

相关问题