c++ - Overloading fstream << operator to save "any" kind of data -
i have created test class has public variable double x. have overloaded ostream << operater able print out variable x. have written external save(filename, object) function save content of object in particular way. use << operator save content of x file. header file (testh.hpp) looks this:
#ifndef testh_hpp_ #define testh_hpp_ #include <iostream> #include <fstream> #include <string> class test { public: double x; friend std::ostream& operator << (std::ostream& os, test& p); inline test(); inline virtual ~test(); }; inline std::ostream& operator << (std::ostream& os, test& p); template <class v> inline void save(const std::string& pname, const v& data); #endif /* testh_hpp_ */ this file defining functions (testc.cpp):
#ifndef testc_cpp_ #define testc_cpp_ #include "testh.hpp" test::test() { x=10; } test::~test() {} std::ostream& operator << (std::ostream& os, test& p) { // output screen os << "test:\t"; os << p.x; return os; } template <class v> void save(const std::string& pname, const v& data) { std::ofstream myfile; myfile.open(pname.c_str()); myfile << data; myfile.close(); std::cout << "====== file saved! ======\npathname: " << pname << std::endl; } #endif /* testc_cpp_ */ and here code test save function (test.cpp):
#include <iostream> #include "testc.cpp" int main () { std::string fn = "test.txt"; int i=1; test a; // std::cout << a; save(fn,a); return 0; } i long list of errors, sais in testc.cpp code compiler cannot myfile << data; command:
in file included ../test.cpp:3:0: ../testc.cpp:33:9: note: ‘const test’ not derived ‘const std::basic_string<_chart, _traits, _alloc>’ myfile << data; could please me resolving issue. thank time.
you streaming test non-const reference:
friend std::ostream& operator << (std::ostream& os, test& p); you want stream const reference:
friend std::ostream& operator << (std::ostream& os, const test& p); ^^^^^^ the error comes fact when call save(), passing in const reference:
template <class v> void save(const std::string& pname, const v& data) { ... myfile << data; // <== data const test& ... }
Comments
Post a Comment