错误:无法从节点*转换为节点 c++?

Error: cannot convert from node* to node c++?

本文关键字:节点 转换 c++ 错误      更新时间:2023-10-16

我是 c++ 的初学者,我正在为学校项目创建自己的 InterlacedList 类,并且我创建了一个 Node 类:

#include "Node.h"
#include "Student.h"
#include <string>
Node::Node()
{
this->student = nullptr;
this->nextName = nullptr;
this->nextYear = nullptr;
this->nextGrade = nullptr;
}
Student Node::getStudent()
{
return this->student;
}
Node Node::getNextName()
{
return this->nextName;
}
Node Node::getNextYear()
{
return this->nextYear;
}
Node Node::getNextGrade()
{
return this->nextGrade;
}

哪个编译很好。

但是在我的隔行列表类中:

#include "InterlacedList.h"
#include "Node.h"
#include "Student.h"
InterlacedList::InterlacedList()
{
this->head = nullptr;
this->tail = nullptr;
}
Node InterlacedList::getHead()
{
return this->head;
}
Node InterlacedList::getTail()
{
return this->tail;
}

我收到此错误: 无法将"((模型::隔行列表*)this)->模型::隔行列表::头"从"模型::节点*"转换为"模型::节点">

错误:无法将"((模型::隔行扫描列表*)this)->模型::隔行列表::尾部"从"模型::节点*"转换为"模型::节点">

我的理解是它应该像 Node 类获取者一样工作。 请帮忙。

查看您的InterlacedList::InterlacedList(),似乎headtail都被定义为指针。您的getHead()返回一个 Node,而不是指向 Node 的指针,这就是弹出错误的原因:您忘记取消引用它。

您可以更改函数,使其返回指针(不要忘记更改头文件中的类定义):

Node* InterlacedList::getHead()

或返回取消引用的对象:

return *(this->head);

但请务必在执行后者之前检查 nullPTR。此外,如果这样做,最好返回对 Node 的引用,而不是返回副本。

看看Node的定义。你忘了在问题中展示它,但我的水晶球告诉我它看起来像这样:

class Node {
// something ...
Node* head;
Node* tail;
// something ...
};

特别注意Node::head(和Node::tail)的类型。类型为Node*。这意味着指向Node的指针

接下来看看getHead(和getTail)的声明:

Node InterlacedList::getHead()

特别注意函数的返回类型。这是Node.这与Node*不同。此返回类型意味着该函数返回一个新的Node对象。它不返回指针。

接下来看看getHead(和getTail)的定义:

return this->head;

好吧,您正在尝试从应该返回Node的函数返回Node*。指针(通常)不能隐式转换为其指针类型。错误很清楚:

could not convert .. from ‘model::Node*’ to ‘model::Node’

解决方案:返回类型与函数的返回类型匹配的对象。一种可能的解决方案是间接指针:

return *this->head;

另一种方法是更改函数的返回类型以匹配要返回的指针。考虑您尝试实施的解决方案。