编译器错误与`<<`

时间:2009-04-02 06:00:30

标签: c++ serialization struct compiler-errors

我一直在努力让这个程序完成,它将多个结构保存到文件中,可以将它们读回并编辑它们,然后将它们全部保存回文件。我一直在研究这个逻辑,更不用说其他人的大量帮助和大量的谷歌搜索时间......现在我收到编译错误。任何帮助都将非常感激。

代码:

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>        ]

3 个答案:

答案 0 :(得分:8)

您没有定义operator<<来指定如何将InventoryItem打印到输出流。您尝试打印它,编译器不知道如何。你需要定义一个像这样的函数:

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

答案 1 :(得分:0)

您正在尝试为您的结构使用<<运算符,但该运算符未针对该类型定义。请尝试输出特定的数据成员。

答案 2 :(得分:0)

&lt;&lt;运算符定义为“左移位”。

IO类重写此运算符并定义&lt;&lt;打印这个结构。

当编译器在右侧看到一个整数项时,它假定你的意思是“左移位机器人”,并且在左侧寻找一个整数但是找到一个IO流对象。

在将整数值发送到流之前,请尝试将整数值转换为字符串。