c++ - 返回值类型与函数类型不匹配(返回类型为嵌套类)
问题描述
我正在通过在 C++ 中实现一组数据结构来练习编程。我目前收到此编译器错误,该错误与函数的返回类型与其声明中指示的类型不同。如果我注释掉Set::findSmallest
set.cpp 底部定义的内容,程序就会编译。
我尝试了许多在 hpp 和 cpp 文件中将 Node 称为 Set::Node 或仅 Node 的变体,但我似乎无法让它工作。
我可以通过不在 Set 类中嵌套 Node 类来解决这个问题,但我想练习使用嵌套类。
set.cpp:86:12: error: out-of-line definition of 'findSmallest' does not match any
declaration in 'Set'
Node* Set::findSmallest(Node* node){
^~~~~~~~~~~~
./set.hpp:12:24: note: type of 1st parameter of member declaration does not match
definition ('Node *' vs 'Set::Node *')
Node* findSmallest(Node* node);
^
set.cpp:90:20: error: cannot initialize return object of type 'Node *' with an lvalue of
type 'Set::Node *'
return nextNode;
^~~~~~~~
2 errors generated.
设置.hpp
#pragma once
class Node;
class Set{
public:
Set();
Set(int x);
void find(int x);
void insert(int x);
Node* findSmallest(Node* node);
private:
class Node {
public:
int value;
Node *smallerNode;
Node *greaterNode;
Node();
Node(int x);
};
Node* rootNode;
Node* nextNode;
};
设置.cpp
#include <iostream>
#include "set.hpp"
using std::cout;
using std::endl;
Set::Node::Node():value(0){
smallerNode = nullptr;
greaterNode = nullptr;
}
Set::Node::Node(int x):value(x){
smallerNode = nullptr;
greaterNode = nullptr;
}
Set::Set(){
rootNode = nullptr;
nextNode = nullptr;
}
Set::Set(int x){
rootNode->value = x;
nextNode = nullptr;
}
void Set::find(int x){
nextNode = rootNode;
while(1){
if(x == nextNode->value){
cout << x << " found!" << endl;
return;
}
else if(x > nextNode->value){
if(nextNode->greaterNode){
nextNode = nextNode->greaterNode;
}
else {
cout << x << " not found!" << endl;
return;
}
}
else {
if(nextNode->smallerNode){
nextNode = nextNode->smallerNode;
}
else {
cout << x << " not found!" << endl;
return;
}
}
}
}
void Set::insert(int x){
if(!rootNode){
rootNode = new Node(x);
return;
}
nextNode = rootNode;
while(1){
if(x == nextNode->value){
cout << x << " already exists!" << endl;
return;
}
else if(x > nextNode->value){
if(nextNode->greaterNode){
nextNode = nextNode->greaterNode;
}
else {
nextNode->greaterNode = new Node(x);
cout << "inserted " << x << endl;
return;
}
}
else {
if(nextNode->smallerNode){
nextNode = nextNode->smallerNode;
}
else {
nextNode->smallerNode = new Node(x);
cout << "inserted " << x << endl;
return;
}
}
}
}
Node* Set::findSmallest(Node* node){
Node* nextNode = node;
while(1){
if(!nextNode->smallerNode){
return nextNode;
}
else {
nextNode = nextNode->smallerNode;
}
}
}
解决方案
这里的错误:
Node* Set::findSmallest(Node* node){
是因为Node
当它被用作返回类型时,它还没有在范围内。你应该写
Set::Node* Set::findSmallest(Node* node){
反而。或者,使用现代功能,
auto Set::findSmallest(Node* node) -> Node* {
推荐阅读
- swift - 如何在 iOS 的 TikTok 上分享视频?
- apache - Magento 2.2.6 + Apache + varnish 4. 似乎 url 重写不起作用
- javascript - 加载静态资源失败
- asynchronous - 带有管道工的异步 API 端点
- c++ - 在多项目 Visual Studio 解决方案中编译不同配置的项目
- python - 使用简单的 Instagram Scraper 时遇到问题
- python - 两个哈希的比较算法
- spring - 如何忽略 JPA 中的某些参数
- java - 在 Java 中,使用 Enums 的更好方法是什么?使用静态常量还是使用构造函数和非文件常量?
- python - 迭代元组内的元组并使用元组内的字符串作为变量