Popgalop
Popgalop

Reputation: 757

Cant use ofstream as field in 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;
}

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.

Upvotes: 2

Views: 1120

Answers (3)

Daniel Frey
Daniel Frey

Reputation: 56921

You can just open the existing object:

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

And you need to avoid calling (or at least requiring) the copy-ctor of your class. Change

FileWriter writer = FileWriter("C:\\Users\\Owner\\Desktop\\Test.bin");

to:

FileWriter writer("C:\\Users\\Owner\\Desktop\\Test.bin");

Upvotes: 2

juanchopanza
juanchopanza

Reputation: 227608

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.

Initialization (preferred option):

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

Move-copy assignment:

file = std::move(openedFile);

Alternatively, you can use the std::ofstream::open method:

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

Upvotes: 4

David G
David G

Reputation: 96865

file = openedFile;

There is only one operator= defined for basic_ofstream, the move-assignment operator. The copy-assignment operator is implicitly deleted, and so this code will not work.

You need to use the member-initializer list to initialize file with the path:

FileWriter(std::string fileName)
    : file(fileName, ios::out | ios::binary)
{
    ...
}

Upvotes: 2

Related Questions