错误:
与“operator<<' (operand types are 'std::ostream' {aka 'std::basic_ostream
”}和“node”不匹配)
#include <iostream>
using namespace std;
class Node
{
int data;
Node *next;
public:
Node(int data1)
{
data = data1;
next = nullptr;
}
};
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6};
Node *rootNode = new Node(arr[0]);
cout << rootNode;
return 0;
}
我期待得到链接列表。
我期待得到链接列表
你为什么会这样期望?您认为
operator<<
如何知道您希望如何打印自定义 Node
类?
您显示的代码可以编译并运行,但输出只是
Node
对象的内存地址,而不是它所保存的 data
值。这是因为存在一个现有的 operator<<
可以打印原始指针。
对于你想要的,你必须告诉操作员你想要如何打印
Node
。您可以通过重载 operator<<
来做到这一点,例如:
#include <iostream>
using namespace std;
class Node
{
int data;
Node *next = nullptr;
public:
Node(int data1) : data(data1) { }
friend ostream& operator<<(ostream &os, const Node &node)
{
os << node.data;
return os;
}
};
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6};
Node *rootNode = new Node(arr[0]);
cout << *rootNode;
delete rootNode;
return 0;
}
如果要打印整个列表,最好将
Node
列表包装在另一个类中,然后为该类重载 operator<<
,例如:
#include <iostream>
using namespace std;
class List
{
struct Node
{
int data;
Node *next = nullptr;
Node(int data1) : data(data1) { }
};
Node *head, *tail;
public:
List() : head(nullptr), tail(nullptr) { }
List(const List&) = delete;
List& operator=(const List&) = delete;
~List()
{
Node *n = head;
while (n)
{
Node *next = n->next;
delete n;
n = next;
}
}
void push_back(int data)
{
Node **n = (tail) ? &(tail->next) : &head;
*n = new Node(data);
tail = *n;
}
friend ostream& operator<<(ostream &os, const List &list)
{
Node *n = list.head;
if (n)
{
os << n->data;
while (n = n->next)
{
os << ',' << n->data;
}
}
return os;
}
};
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6};
List list;
for(int elem : arr)
list.push_back(elem);
cout << list;
return 0;
}