不匹配&#39;运营商&lt;&lt;&#39; (操作数类型是&#39; std :: fstream {aka std :: basic_fstream <char>}&#39;&#39; Word&#39;)

时间:2017-05-05 17:36:33

标签: c++ compiler-errors

我收到以下编译错误:no match for 'operator<<' (operand types are 'std::fstream {aka std::basic_fstream<char>}' and 'Word')

此错误的原因是什么?

以下是重现错误的最小示例:

#include <fstream>
#include <cstring>

struct Word
{
    char word[10];
    char mean[20];
};

Word word;

void writeDataToFile()
{
    std::fstream fileOutput("data.txt", std::ios::out | std::ios::binary);
    // error handling left out for simplicity
    fileOutput << word << std::endl;
}

int main()
{
    strcpy(word.word, "Apple");
    strcpy(word.mean, "Trai tao");
    writeDataToFile();
    return 0;
}

1 个答案:

答案 0 :(得分:2)

您需要重载struct Word的输出运算符,因为您在行fileOutput << a << endl;上使用它。在output overloading on tutorialspointoperator overloading on cppreference上查看这两个链接。