【问题标题】:Compiler error with `<<``<<` 的编译器错误
【发布时间】:2009-04-02 06:00:30
【问题描述】:

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

代码:

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

【问题讨论】:

  • 考虑使用较短的标题,并将当前标题移动到问题的正文中。很难阅读这个问题,因为标题格式不太适合这么长的内容。
  • 啊抱歉!我认为“帮助解决这个编译错误”太含糊了。我正在尝试尽可能具体!
  • 尝试类似“'

标签: c++ serialization struct compiler-errors


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 等等……你什么意思?你能提供一个简短的例子吗?对不起!
    • 类似out &lt;&lt; *i.Item 而不是out &lt;&lt; *i
    【解决方案3】:

    IO 类覆盖此运算符并定义

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

    尝试将整数值显式转换为字符串,然后再将其发送到流。

    【讨论】:

    • 评估双方。将 int 插入流中是非常好的 - 例如:std::strstream str;str
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-25
    • 1970-01-01
    • 2013-05-05
    • 2011-01-02
    • 2011-12-22
    • 2011-08-10
    • 2013-07-09
    相关资源
    最近更新 更多