2009-04-02 18 views
0

私は、このプログラムが複数の構造体をファイルに保存して読み込み、編集してからファイルに保存するところに取り組んでいます。私は他人からの助けと数多くのグーグル・アワーの助けはもちろん、コンパイル・エラーに陥っています。どんな助けでも大歓迎です。コンパイラエラー `<<"

コード:

template<typename T> 
void writeVector(ofstream &out, const vector<T> &vec); 

struct InventoryItem { 
    string Item; 
    string Description; 
    int Quantity; 
    int wholesaleCost; 
    int retailCost; 
    int dateAdded; 
} ; 


int main(void) 
{ 
    vector<InventoryItem> structList; 
    ofstream out("data.dat"); 
    writeVector(out, structList); 
    return 0; 
} 

template<typename T> 
void writeVector(ofstream &out, const vector<T> &vec) 
{ 
    out << vec.size(); 

    for(vector<T>::const_iterator i = vec.begin(); i != vec.end(); i++) 
    { 
     out << *i; // error C2679 
    } 
} 

コンパイラエラー:

1>.\Project 5.cpp(128) : error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'const InventoryItem' (or there is no acceptable conversion) 
// listed overload variants skipped 
1>  while trying to match the argument list '(std::ofstream, const InventoryItem)' 
1>  .\Project 5.cpp(46) : see reference to function template instantiation 'void writeVector<InventoryItem>(std::ofstream &,const std::vector<_Ty> &)' being compiled 
1>  with 
1>  [ 
1>   _Ty=InventoryItem 
1>  ] 
+0

短いタイトルを使用し、現在のタイトルを質問の本文に移動することを検討してください。タイトルの書式設定は長続きするものにはあまり適していないため、この質問を読むのは難しいです。 –

+0

ああ申し訳ありません!私は "このコンパイルエラーのヘルプ"があまりにも曖昧だと思った。私は可能な限り具体的にしようとしています! – OneShot

+0

"<< '演算子でコンパイルエラー" – Colin

答えて

8

InventoryItemを出力ストリームに出力する方法を指定するoperator<<が定義されていません。あなたはそれを印刷しようとし、コンパイラは方法を知らない。あなたはこの1のような関数を定義する必要があります。

std::ostream& operator<<(std::ostream &strm, const InventoryItem &i) { 
    return strm << i.Item << " (" << i.Description << ")"; 
} 
0

あなたは、構造体のための<<演算子を使用しようとしているが、そのオペレータはそのタイプのために定義されていません。代わりに特定のデータメンバーを出力してみてください。

+0

待って...どういう意味ですか?簡単な例を教えてください。ごめんなさい! – OneShot

+0

'out << * i'ではなく' out << * i.Item'のようなものです。 – Kalium

0

< <演算子は「シフトビット左」と定義されます。

IOクラスはこの演算子をオーバーライドし、< <を定義すると、この構造体を印刷することを意味します。

コンパイラが整数項目を右側に見ると、 "シフトボットが残っている"とみなされ、左側のintgerを探していますが、代わりにIOストリームオブジェクトが見つかります。

ストリームに送信する前に、整数値をstringに変換してみてください。

+0

両側が評価されます。 intにストリームを挿入するのはまったく問題ありません。例えば std :: strstream str; str << int(5); – qwerty

関連する問題