形成一个返回指向包含类的指针的函数?

问题描述:

我想使用指向节点的链接列表。 List是Node的容器类。我试图格式化查找函数的列表,当链接列表中找到该节点时,返回指向节点的指针。但是,我不断收到错误,说没有类型说明符。 (错误显示在下面链接的屏幕截图中,主要查看Node.h中的第10行和第17行)。我如何正确格式化以摆脱错误? https://imgur.com/vicL8FS形成一个返回指向包含类的指针的函数?

NODE.H //Both class declarations contained here 
class list //container class 
{ 
public: 
    list(); 
    ~list(); 
    void insert(string f, string l, int a); 
    node *find(string first, string last); //Pointer to contained class 
private: 
    node *head; //errors here 
    int length; 
}; 
class node 
{ 
    friend list; 
public: 
    node();       // Null constructor 
    ~node();       // Destructor 
    void put(ostream &out);   // Put 
    bool operator == (const node &); // Equal 
private: 
    string first, last; 
    node *next; 
}; 

NODE.CPP 

#include "Node.h" 
    node list::*find(string first, string last) 
    { 
     return NULL; //logic not written yet 
    } 
//MAIN 
p = a.find(first, last); //p is a pointer to node, a is a list. 
+0

尝试'node * list :: find(string first,string last)'。 –

+0

这不起作用。它只是增加了另一个错误 –

+0

也许,但是'node * list :: find(string first,string last)'是无效的。因为返回类型是'node *',函数名是'list :: find'。你不能混用它们。 –

眼下nodelist后定义和名称node不知道它开始分析list类主体时,编译器。您需要添加一个向前声明:

class node; 

class list 
{ 
... 

所以node将是正确识别的类型名称。

+0

这似乎清除了错误。要明确,这不会重新定义任何变量?我不必移动节点定义下的整个列表定义? –

+0

不,这不会重新定义任何东西。前向声明只会将'node'识别为类型名称。在'node'定义下移动整个'list'定义将是解决错误的另一种方法。请注意'friend list;'声明不需要'list'已经被声明。 – VTT

错误的原因是,当编译器编译类list的定义时,它不知道名称node是如何声明的。

有几种方法可以解决问题。你可以使用详细的类名。

例如,您可以首先定义类节点并使用详细的类名列表。

class node 
{ 
    friend class list; 
public: 
    node();       // Null constructor 
    ~node();       // Destructor 
    void put(ostream &out);   // Put 
    bool operator == (const node &); // Equal 
private: 
    string first, last; 
    node *next; 
}; 

class list 
{ 
    //... 
}; 

或者你也可以在类list定义使用类node的详尽的名字。例如

class list //container class 
{ 
public: 
    list(); 
    ~list(); 
    void insert(string f, string l, int a); 
    class node *find(string first, string last); //Pointer to contained class 
private: 
    class node *head; 
    int length; 
}; 

class node 
{ 
    //... 
}; 

或者您可以使用node类的前向声明。

class node; 

class list //container class 
{ 
public: 
    list(); 
    ~list(); 
    void insert(string f, string l, int a); 
    node *find(string first, string last); //Pointer to contained class 
private: 
    node *head; 
    int length; 
}; 

class node 
{ 
    //... 
}; 

或者您可以使用类list的前向声明。

class list; 

class node 
{ 
    friend list; 
public: 
    node();       // Null constructor 
    ~node();       // Destructor 
    void put(ostream &out);   // Put 
    bool operator == (const node &); // Equal 
private: 
    string first, last; 
    node *next; 
}; 

class list 
{ 
    //... 
};