类中的链接列表,应该通过类中的函数调用

时间:2012-09-07 07:56:43

标签: c++ linked-list

这是头文件

class sv1{
private:
  struct Node{
          string title;
          Node* next;
              };
public:
void InsertAfter(Node **head, string title);
void getMetadata(string t);
void q_folder(string t_q);

这是cc文件的方式

void sv1::getMetadata(string t)
{
Node *head=NULL;
title=t;
q_folder(title);
}
void sv1::q-folder(string t_q)
{
InsertAfter(&head,t_q);
}
void sv1::insertAfter(Node **head,string title)
{
if (head==NULL)
{
Node* temp=NULL;
temp=new Node;
temp->title=title;
*head=temp;
}
else{
Node *temp= new Node;
temp= new Node;
temp->title=title;
temp->next=(*head)->next;
(*head)->=temp;

}
}

错误表示头部未在函数q_folder中声明。是什么导致的,我该如何解决?

2 个答案:

答案 0 :(得分:5)

在你的方法q-folder中,你用“& head”调用insertAfter。在任何类方法中头部都可识别的唯一方法是

  1. 本地
  2. 参数
  3. 类成员(继承或其他)
  4. 全球(但是,请考虑这是禁忌)
  5. 看到三者中没有一个,它不知道“和头”是什么意思。另外,正如提到的hmjd更正,您声明的方法都没有被标记为属于该类。你把它们写成了独立于任何类的独立方法。为了表明它们属于类sv1,您需要在方法名称的开头添加“sv1 ::”。

答案 1 :(得分:0)

我认为你正在追求一种错误的模式。为什么要在类的私有部分中定义Node结构!通常的模式是您必须为Node和LinkedList本身分隔类。请创建另一个封装节点的类。您也可以使用模板实现它,以支持不同的数据类型。

head也是一个内部变量。你不应该接受它作为函数参数。这不是面向对象的,因为您的链表(如果有效)不一致,并且所有定义变量都可以更改。您需要为LinkedList创建head私有。在这里你可以找到一些例子:

Simple C/C++ Linked List

How to create Linked list using C/C++