【问题标题】:Linked lists using nested classes?使用嵌套类的链表?
【发布时间】:2014-08-21 09:19:50
【问题描述】:

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

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

但是一旦我尝试修改head的数据成员:data指向接收到的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

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

【问题讨论】:

  • 为什么不使用std::list
  • 不能——这是作业的规则。

标签: c++ linked-list


【解决方案1】:

在这段代码中:

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

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

也许你的本意是这样的:

head = new Node();

setHead之前。

【讨论】:

  • 谢谢,成功了。我真的很惭愧这是问题所在。
猜你喜欢
  • 1970-01-01
  • 2016-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-28
  • 1970-01-01
相关资源
最近更新 更多