0

クラスでは、作成したオブジェクトを出力できるように、<<演算子をオーバーロードしようとしています。私はこれを宣言して追加しました

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

1 に答える 1

1

クラス WORD の << をオーバーロードする場合、パラメーターは 'WORD' 型である必要があります。そのような質問をする前に、最初に << のオーバーロードを検索する必要があると思います。:-)

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;
}
于 2012-06-05T02:25:26.097 に答える