【问题标题】:no matching function call std::basic_ofstream<char>::write() [duplicate]没有匹配的函数调用 std::basic_ofstream<char>::write() [重复]
【发布时间】:2016-07-20 18:13:36
【问题描述】:

我正在尝试在这里完成二进制 i/o,但我不断收到此错误...

no matching function for call to 'std::basic_ofstream<char>::write(int*,unsigned int)'

no matching function for call to 'std::basic_ofstream<char>::write(double*,unsigned int)'

这是我的代码...

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    int x = 123;
    double fx = 12.34;
    ofstream myfile("filename.dat", ios::out | ios::binary);
    myfile.write(&x, sizeof(x));
    myfile.write(&fx, sizeof(fx));
    myfile.close();
    return 0;
}

我发现了多个其他具有相同情况的帖子,但他们的解决方法通常是输入...

ofstream myfile(filename.c_str(), ios::out | ios::binary);

当我多次尝试时,编译器仍然对我尖叫。我使用 QT creator 作为我的 IDE,我已经验证它使用的是 C++11。并且还在 Code::Blocks 中运行相同的代码并得到相同的错误。它不喜欢我传递给它的文件名参数。我认为这与第一个参数是ofstream open()的成员函数的const char有关?!

void open(const char *filename, [int mode], [int prot]);

我在这里不理解/错过了什么?

【问题讨论】:

  • 您缺少的是您能想到的每种类型都没有write 重载。如果你想做二进制 I/O,你应该通过将指向保存对象的内存的指针转换为 const char * 来明确它。

标签: c++ qt c++11


【解决方案1】:

write()是一个输出字符的函数,它不会应用任何格式,你需要自己进行格式。

该函数需要一个const char* 参数。它不需要指向其他类型的指针,需要先进行转换。

请参阅here 了解更多详情。

如果您希望流格式化输出,则流运算符&lt;&lt; 更适合。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-06
    • 1970-01-01
    • 2020-07-13
    • 1970-01-01
    • 2015-06-02
    相关资源
    最近更新 更多