Search code examples
c++fstream

I'm confused why this line show me the error in PC but Mac can work with it


On outfile = fstream(filename); There shows me private 'ios_base::operator=(const ios_base&)' is inaccessible, I don't know how to solve it, I'm using clion to compile it, but for Mac, no problem on it

class ErrorHandler{
private:

    std::fstream outfile;

public:
    ErrorHandler(char const filename[]) {

        outfile = fstream(filename);

        outfile << filename << " opened"  << endl;
    }

    ~ErrorHandler(){

    }

    void warn(char const message[]){

        cout << message << endl;

        outfile << message << endl;

    }


    void terminate(char const message[]){

        cout << message << endl;

        outfile << message << endl;

        exit(1);

    }
};

int main() {

    ErrorHandler h("log.txt");

    h.warn("Error 10: this is your first warning");
    h.warn("Error 20: I warned you");
    h.terminate("Error 30:  Told you so.");

    return 0;
}

Solution

  • Your problem is that you can't assign one fstream to another, which is exactly what is happening when you assign it.

    You've a few options, but the easiest is to declare outfile as an std::fstream*, and then in your constructor:

    outfile = new fstream(filename);
    

    Remember to delete it in your destructor.