问题描述
我在c ++中创建一个用于编写文件的类,并且我有这个代码到目前为止,
I am creating a class for writing file in c++, and i have this code so far,
#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;
}
但由于某种原因,它不允许我有一个stream字段,我试试它说,错误1错误C2248:'std :: basic_ofstream< _Elem,_Traits> :: operator =':不能访问私人成员声明在类'std :: basic_ofstream< _Elem,_Traits& c:\users\owner\documents\visual studio 2012 \projects\bytetests\bytetests \bytetests.cpp 25 1
我需要这个,因为我的类中的函数需要操纵这个流。我不明白为什么这么难做。
but for some reason, it wont let me have an ofstream field, and when i try it says, 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
I need this because functions in my class need to manipulate this stream. I don't see why this so hard to do.
推荐答案
您不能复制或分配 std :: ofstream
,这意味着你不能这样做:
You can't copy or assign an std::ofstream
, which means you can't do this:
file = openedFile;
您需要正确初始化或移动拷贝分配。
You need to either initialize it correctly, or move-copy-assign.
初始化(首选选项):
FileWriter(string fileName) : file("data.bin", ios::out | ios::binary)
{
...
}
移动副本分配:
file = std::move(openedFile);
或者,您可以使用 std :: ofstream :: open
方法:
Alternatively, you can use the std::ofstream::open
method:
file.open("data.bin", ios::out | ios::binary);
这篇关于不能使用stream作为c ++中的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!