我有类 Agency
,它有一个私有(private)嵌套类 Node
,应该用于构建 Client
对象的链表。
为了添加一个节点,我需要使用一个重载的 +=
运算符来接收一个 Client
对象。
当我想添加第一个对象时:该函数调用 Node
类的 setHead
成员。
但是一旦我尝试修改 head
的数据成员:data
指向接收到的 Client
对象和 next
到 NULL
发生运行时错误。
我不知道出了什么问题,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/