【发布时间】:2021-11-22 12:57:54
【问题描述】:
我收到错误 expression must have a class type but it has type "Node * const"。我的代码如下所示:
编辑:忘了提到错误来自:if(L1.head.value == L2.head.value)
bool operator== (const List L1, const List L2) {
bool boolean = false;
// If both list have the same number of elements
if(L1.n == L2.n) {
// Until the list is empty
while(IsEmpty(L2), IsEmpty(L2)) {
// If the current values are the same, sets boolean to true, remove head of list and then loops
if(L1.head.value == L2.head.value) {
boolean = true;
L1 = Rest(L1);
L2 = Rest(L2);
}
else {
return false;
}
}
return boolean;
}
// Exception : If the list don't have the same number of elements they can't be equal
else {
return false;
}
}
结构如下:
typedef struct {
int value;
struct Node * succesor;
} Node;
typedef struct {
struct Node * head;
struct Node * tail;
int n;
} List;
我导入:
#include <iostream>
#include <stdlib.h>
#include <stdbool.h>
#include <string>
using namespace std;
当前的 IsEmpty() 和 Rest() 也是 bool 类型和 list 类型的方法。他们目前什么都不做。 当 L1 和 L2 都被定义为 List 结构时,我不知道为什么它需要一个类类型。 最后一个问题,代码会做我想做的事吗?我想重写 == 运算符,以便能够比较两个 List 类型的列表。
【问题讨论】:
-
仔细阅读错误信息会发现问题不是
L1,而是head。 -
#include <stdbool.h>-- 看起来您在编写 C++ 代码时正在尝试利用您在 C 中学到的知识。或者您正在使用 C 作为指导来学习 C++。typedef struct是您正在学习或使用 C 的另一种赠品。不要这样做,因为 C 和 C++ 是两种不同的语言。不需要stdbool.h,因为bool是原生C++ 类型。 -
你说得对,我是从我的学校独立学习 C++,我的学校教 C。对于 bool 我不知道,对于 typedef,我知道你也可以使用 struct Name {};问题是我需要在每个声明中使用 struct Name name_of_variable。
-
在不使用 C 作为指南的情况下学习 C++。没有初学者 C++ 程序员会使用
stdbool.h,正如他们将在第一周了解到的那样,bool是本机类型——他们可能根本不知道stdbool.h甚至存在,因为它们不是 学习 C,但学习 C++。通过使用 C 作为指导,你会无意中开始使用你习惯的东西,即stdbool.h、typedef struct,我敢打赌malloc也不甘落后。这就是你会发现自己陷入的两难境地。 -
不要将您的问题编辑到使现有答案无效的程度。相反,为您的新问题开始一个新问题。
标签: c++ class operator-overloading singly-linked-list