c++ - trying to implement simple ostream singleton class -


i want implement singleton class receives file path parameter. tried write following code . know doesn't work , not can't find why..

class outputdata {     std::fstream ofile;     std::ostream iout;     static outputdata *odata;     outputdata(const char* path):iout(std::cout), ofile(path) {         if (ofile.is_open()) {             iout = ofile;         }     } public:     static void print(std::string s) {         iout << s;     } }; 

in .cpp

outputdata *outputdata::odata = nullptr; 

and on want every class have ability write stream.

thanks

you can't take std::istream or std::ostream instance copy, member variables should references or pointers:

class outputdata {     std::fstream* ofile;     std::ostream* iout;     static outputdata *odata;     outputdata(const char* path):iout(nullptr), ofile(nullptr) {         ofile = new fstream(path);         if (ofile->is_open()) {             iout = ofile;         }         else {             delete ofile;             ofile = nullptr;             iout = &cout;         }     }     // take care provide appropriate destructor     ~outputdata() {         delete ofile;     }  }; 

also regarding singleton design, i'd rather recommend scott meyer's singleton idiom:

class outputdata { public:     static outputdata& instance(const char* path) {         static outputdata theinstance(path)         return theinstance;     }     // make print non-static member function     void print(std::string s) {         iout << s;     } }; 

though approach weirdly looks opposite, what's considered canonical solution.


Comments

Popular posts from this blog

javascript - Google App Script ContentService downloadAsFile not working -

javascript - Function overwritting -

c# - Exception when attempting to modify Dictionary -