重载非成员运算符的问题<< in a linkedlist class in c++98

问题描述 投票:0回答:1

有人可以帮我解决这个问题吗?对于背景信息,我有三个类,

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 <<

但是没有用。

c++ operator-overloading c++98
1个回答
0
投票
首先,您的

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; }

© www.soinside.com 2019 - 2024. All rights reserved.