gpt4 book ai didi

c++ - 不能在 C++ 中使用 ofstream 作为字段

转载 作者:行者123 更新时间:2023-11-30 00:52:17 24 4
gpt4 key购买 nike

我正在创建一个用 C++ 编写文件的类,到目前为止我有这段代码,

#include "stdafx.h"
#include <iostream>
#include <string>
#include <stdlib.h>
#include <fstream>

using namespace std;

class FileWriter
{
private:
bool isLittleEndian;
ofstream file;

public:
FileWriter(string fileName) : file("data.bin", ios::out | ios::binary)
{
int i = 1;
char *p = (char *)&i;

if(p[0] == 1)
isLittleEndian = true;
}

void writeByte()
{

}

void writeShort()
{

}

void writeInt()
{

}

void writeLong()
{

}

void writeUnsignedByte()
{

}

void writeUnsignedShort()
{

}

void writeUnsignedInt()
{

}

void writeUnsignedLong()
{

}

void writeFloat()
{

}

void writeDouble()
{

}

void writeString()
{

}

void closeFile()
{
file.close();
}
};

int main()
{
FileWriter writer = FileWriter("C:\\Users\\Owner\\Desktop\\Test.bin");
writer.closeFile();
return 0;
}

但出于某种原因,它不会让我有一个 ofstream 字段,当我尝试时它说,Error 1 error C2248: 'std::basic_ofstream<_Elem,_Traits>::operator =' : cannot access private member declared in class 'std::basic_ofstream<_Elem,_Traits>' c:\users\owner\documents\visual studio 2012\projects\bytetests\bytetests\bytetests.cpp 25 1我需要这个,因为我类的函数需要操纵这个流。我不明白为什么这很难做到。

最佳答案

您不能复制或分配 std::ofstream,这意味着您不能这样做:

file = openedFile;

您需要正确初始化它,或者移动复制分配。

初始化(首选选项):

FileWriter(string fileName) : file("data.bin", ios::out | ios::binary)
{
...
}

移动复制赋值:

file = std::move(openedFile);

或者,您可以使用 std::ofstream::open 方法:

file.open("data.bin", ios::out | ios::binary);

关于c++ - 不能在 C++ 中使用 ofstream 作为字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19437258/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com