问题描述
当我尝试在Node.cpp中编写getNext()方法时,出现以下错误。请检查Node.cpp getNext()方法。我正在尝试为双链表编写吸气剂和吸气剂,这就是我所拥有的。
class Node
{
private:
string phonenumber;
string name;
string type;
Node* next;
Node* prev;
public:
Node(string name,string phonenumber,string type);
void setNext(Node ptr);
Node getNext();
string getName();
void setName(string name);
string getPhone();
void setPhone(string phonenum);
string getType();
void setType(string type);
};
#endif
Node.cpp
#include "Node.h"
Node::Node(string name,string type)
{
//constructor
}
Node::Node(string name,string type)
{
}
void Node::setNext(Node ptr)
{
}
当我尝试在Node.cpp中编写getNext()方法时,出现以下错误。请检查Node.cpp getNext()方法。我正在尝试为双链表编写吸气剂和吸气剂,这就是我所拥有的。
Node Node::getNext()
{
return next; /**/ this line gives me an error (it says no suitable constructor exists for Node* to Node)
}
解决方法
您的变量next
是Node*
,而在函数中,您返回的是Node
。
将Node
更改为Node*
:
Node* Node::getNext()
{
return next;
}
,
该错误表示它不知道将Node
(Node的一个实例)转换为Node*
(指向Node
(或nullptr
的实例的指针)
这些代码片段将使您摆脱困境:
//In the class definition:
Node* getNext();
//...
// The function definition:
Node* Node::getNext(){
return this->next; //or just return next; if you prefer.
}
在C ++中,对象与指向该对象的指针之间存在很大的差异。
一旦您了解了这个概念,您就可以在掌握C ++方面取得巨大进步。
我不知道您的背景,但是Java掩盖了这一点,因为所有对象变量都是有效的 指针(用C ++术语)。
但是在C ++中,区别很重要,您可以有一个对象变量,一个指针或一个引用。但是指针是双向链表中next
和prev
的正确答案。
注意:一个更好的答案是Node* getNext() const;
,但稍后再担心!