【发布时间】:2014-10-15 07:05:35
【问题描述】:
我有三个类:ClientDatabase 和 Node 作为 Database 中的嵌套类。
Node 的数据是指向Client 对象的指针,Client 类有自己的重载<< 运算符。
我需要一个重载的<< 运算符来输出所有链表的数据。
我遇到的问题是无法使用<< 重载运算符遍历所有列表,我能做的最好的事情是使用getData 成员输出头节点的数据,出于某种原因Node::Print不会输出所有列表Client *data。
这是Database 类和提到的两个方法<< 和print()。
数据库.h
class Databse
{
private:
class Node //node as nested class
{
public:
Node();
void setNode(Client*&);
Node* nextNode(Node*&);
Client getData();
void print (Node*);
private:
Client* data; //holds pointer to Client object
Node* next; //holds pointer to next node in list
};
Node *head; //holds the head node
int nClients;
public:
Databse();
friend ostream& operator<<(ostream&, const Databse&);
Node* getHead() const;
~Databsey();
};
Databse.cpp相关方法:
ostream& operator<<(ostream& out, const Databse& obj)
{
out << endl << "The databse holds" << obj.nClients << " clients:" << endl;
out << obj.head->getData();
obj.head->print(obj.getHead());
return out;
}
void Database::Node::print (Node* str)
{
Node* current = str ;
while (current->next)
{
cout << current->data;
current = current->next;
}
}
谢谢。
【问题讨论】:
标签: c++ linked-list operator-overloading