如何重载运算符<<有链表?

时间:2012-06-05 01:55:17

标签: c++ linked-list operator-overloading

对于课程,我试图重载<<运算符,所以我可以打印出我创建的对象。我声明并添加到此

WORD you; //this is a linked list that contains 'y' 'o' 'u'

我想要这样做

cout << you; //error: no operator "<<" matches theses operands

我必须将插入操作符作为友元函数重载,并使用链接来打印单词。

我已经声明并定义了重载函数,但它仍然无效。这是类声明文件,后跟带有函数

的.cpp文件
#include <iostream>

using namespace std;
#pragma once

class alpha_numeric //node
{
public:
char symbol; //data in node
alpha_numeric *next;//points to next node
};

class WORD
{
public:
WORD(); //front of list initially set to Null
//WORD(const WORD& other);
bool IsEmpty(); //done
int Length();
void Add(char); //done
void Print(); //dont
//void Insert(WORD bword, int position);
//WORD operator=(const string& other);

friend ostream & operator<<(ostream & out, alpha_numeric *front);//******************<-----------------

private:
alpha_numeric *front; //points to the front node of a list
int length;

}; 

在.cpp文件中,我将*front放在参数中,因为当我尝试在函数内部使用它时,它没有定义front,即使我在类中声明了它。然后我尝试了这个。我不知道它是否正确。

ostream & operator<<(ostream & out, alpha_numeric *front)
{
alpha_numeric *p;
for(p = front; p != 0; p = p -> next)
{
    out << p -> symbol << endl;
}
}

1 个答案:

答案 0 :(得分:1)

如果你想重载&lt;&lt;对于WORD类,参数必须是'WORD'类型。我认为你必须搜索重载&lt;&lt;在问这样的问题之前。 : - )

class WORD
{
friend ostream & operator<<(ostream & out, const WORD& w);
}

ostream & operator<<(ostream & out, const WORD& w)
{
alpha_numeric *p;
for(p = w.front; p != 0; p = p -> next)
    out << p -> symbol;
out<<endl;
return out;
}