對於班級,我試圖超載< <操作員,以便我可以打印出我創建的對象。我聲明,並加入到這一如何重載operator <<與鏈表?
WORD you; //this is a linked list that contains 'y' 'o' 'u'
,我想這樣做
cout << you; //error: no operator "<<" matches theses operands
我要插入運算符重載爲友元函數與鏈接打印字。
我已經聲明並定義了重載函數,但它仍然不起作用。下面是類的聲明文件,然後用功能
#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文件中.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;
}
}
爲什麼不創建'ostream&operator <<(ostream&out,WORD&word)'? –
@SevaTitov它必須作爲一個朋友功能來實現,它在作業方向 – Mike