user1290126
user1290126

Reputation: 53

how to initialize static reference to std::ofstream?

I have a class Cl with public member

static std::ofstream &_rout;

In main file

ofstream out("output.txt");
ofstream& Cl::_rout(out);

But I have a compilation error: illegal definition or redefinition. How can I correct it?

Upvotes: 1

Views: 10990

Answers (3)

LautaroOsinaga
LautaroOsinaga

Reputation: 49

Try this.

Logger.h

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

using namespace std;

class Logger{

    public:
            static void open( const string & logFile);
            static void close();
            // write message
            static void write( const string & message);

    private:
          Logger();
          ofstream fileStream;
          //Logger instance (singleton)
          static Logger instance;
};

Logger.cpp

#include "Logger.h"

Logger Logger::instance;

Logger::Logger(){}

void Logger::open( const string& logFile){
   instance.fileStream.open(logFile.c_str());
}
void Logger::close(){
    instance.fileStream.close();

} 
void Logger::write(const string& message){
    ostream& stream =  instance.fileStream ;
    stream << message<< endl;
}

main.cpp

#include "Salida/Logger.h"
int main(){
    Logger::open(path);
    Logger::write("text");
    Logger::close();
    return 0;

}

Upvotes: 4

Daniel Trebbien
Daniel Trebbien

Reputation: 39208

Well, you could use the following approach:

#include <fstream>

class CI
{
public:
  static std::ofstream &_rout;
};

static std::ofstream out("output.txt");

std::ofstream& CI::_rout = out;

int main()
{
}

The problem with this, however, is that the name of the output file is fixed (hard-coded into the program).

I suggest that you use a pointer instead of a reference:

#include <cstddef>
#include <fstream>

class CI
{
public:
  static std::ofstream *_rout;
};

std::ofstream* CI::_rout = NULL;

int main()
{
  const char *output_file = "output.txt";
  std::ofstream out(output_file);
  CI::_rout = &out;
}

Upvotes: 0

Attila
Attila

Reputation: 28762

You can only set the reference at the static/global scope

#include<CL.h>
ofstream& Cl::_rout(out);
int main() {
  // ...
}

It is not possible to re-set a reference after it was declared (and initialized). You could achieve what you are after by using pointers instead of references:

class Cl {
  static std::ofstream* _rout;
};
std::ofstream* CL::_rout = NULL;

int main() {
  ofstream out("output.txt");   
  Cl::_rout = &out;   
}

Note that the pointer will be valid only until out goes out of scope. If this is an issue, allocate the memory dynamically:

  ofstream* out = new ofstream("output.txt");   
  Cl::_rout = out;   

And don't forget to delete it when you no longer need the object to avoid memory leaks

Upvotes: 3

Related Questions