c++ - Overriding ofstream operator<< -


why still have error: exepected identifier in std::ofstream << val on line below? msvc.

std::ostream& operator<< (bool val) { m_lock.lock(); std::ofstream << val; m_lock.unlock(); return *this; } 
class ofstreamlog : public std::ofstream  {      private:          std::mutex m_lock;      public:          ofstreamlog() : std::ofstream() { }         explicit ofstreamlog(const char* filename, ios_base::openmode mode = ios_base::out) : std::ofstream(filename, mode) { }          std::ostream& operator<< (bool val) { m_lock.lock(); std::ofstream << val; m_lock.unlock(); return *this; }         std::ostream& operator<< (short val);         std::ostream& operator<< (unsigned short val);         std::ostream& operator<< (int val);         std::ostream& operator<< (unsigned int val);         std::ostream& operator<< (long val);         std::ostream& operator<< (unsigned long val);         std::ostream& operator<< (float val);         std::ostream& operator<< (double val);         std::ostream& operator<< (long double val);         std::ostream& operator<< (void* val);         std::ostream& operator<< (std::streambuf* sb);         std::ostream& operator<< (std::ostream& (*pf)(std::ostream&));         std::ostream& operator<< (std::ios& (*pf)(std::ios&));         std::ostream& operator<< (ios_base& (*pf)(ios_base&));      }; 

std::ofstream type name. can't call nonstatic method or operator without object.

in case want std::ofstream::operator<<(val); instead of std::ofstream << val;.


explanation:

when want call method of parent class method of child class, this:

class {     void func() {} };  class b {     void test()     {         func(); //     } }; 

but if child class have method same name (more precisely, same signature (it means, same name , argument types)), called instead of parent's one. explicitly call method of parent class, can use syntax:

class {...}; class b {     void test()     {         a::func(); // notice `a::`     } }; 



now let's talk operators. when want call operator, use object name it, object << 10;. when want call operator of class (or it's parent) method of class, should use full operator syntax:

class {     operator<<(int){} }; class b {     void test()     {         operator<<(10); // <-----         *this << 10; // can     } }; 



now, combine these 2 techniques:
if child class have operator same signature parent's 1 , want call operator of parent, this:

class {...}; class b {     void test()     {         a::operator<<(10); // notice `a::`         *(a*)this << 10; // can     } }; 

Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -