有人可以帮我解决这个问题吗?对于背景信息,我有三个类,
Account.h
和 Account.cpp
,Node.h
和 Node.cpp
,LinkedList.h
和 Linkedlist.cpp
,以及包含 demo.cpp
的 int main()
。当前所有功能都在工作,除了打印出链表,这是我的问题的基础。
问题具体说:
实现一个非成员重载
函数,它使用operator <<
中的operator <<
,允许您执行如下操作:Account
cout << MyLinkedList << endl;
我从
LinkedList.cpp
和 Account.cpp
复制了我的代码中与这个问题相关的特定部分,因为如果我把它全部粘贴在这里会太长。
LinkedList.cpp
中带有重载
operator <<
函数“尚未工作”的代码如下所示: 请注意
value_type
是
Account
的类型定义。
#include "LinkedList.h"
LinkedList::value_type LinkedList::getCurrent() const {
if (current != NULL) {
return current->getData();
} else {
return value_type();
}
}
ostream& operator << (ostream& out, const LinkedList list) { // not working, compile error!
value_type current = getCurrent();
while (current != NULL) {
out << "(" << acc.getName() << "," << acc.balance() << ")" << endl;
}
return out;
}
来自Account.cpp
的代码如下所示:
ostream& operator << (ostream& out, const Account acc)
{
out << "(" << acc.getName() << "," << acc.balance() << ")" << endl;
return out;
}
那么,在Account
类非成员重载运算符
<<
中使用
LinkedList
函数是否可以使用
<<
非成员重载
getCurrent()
运算符?如果是这样,怎么样?或者,我是否需要创建自己的重载
operator <<
使用
Node::getData()
方法而不是
value_type::getCurrent()
方法?我尝试了上面的重载代码
operator <<
但是没有用。
operator<<
应该通过常量引用而不是值来获取第二个参数,例如:
ostream& operator << (ostream& out, const Account& acc)
ostream& operator << (ostream& out, const LinkedList& list)
其次,是的,可以在 Account
运算符中使用
LinkedList
运算符。您需要等价于以下内容(因为您没有提供完整的类声明):
ostream& operator << (ostream& out, const LinkedList& list) {
LinkedList::Node *cur = list.getFirst();
while (cur != NULL) {
out << cur->getData();
cur = cur->getNext();
}
return out;
}