I want to use std::ostream like this:
int main()
{
std::ostream os;
os << "something ..." << std::endl;
return 0;
}
There's an error said that the ostream constructor is protected:
error: ‘std::basic_ostream<_CharT, _Traits>::basic_ostream() [with _CharT = char; _Traits = std::char_traits]’ is protected.
But I remember operator<< could be overloaded like this:
// In a class.
friend std::ostream & operator<<(std::ostream& out, const String & s) {
out << s.m_s;
return out;
}
Any advice on why my code doesn't work?
The std::ostream, the std::istream or the std::iostream are base classes of stream types (e.g. std::stringstream, std::fstream, etc.) in the Standard Library. These classes are protected against instantiation, you can instantiate their derived classes only. The error message
error: 'std::basic_ostream<_CharT, _Traits>::basic_ostream() [with _CharT = char; _Traits = std::char_traits]' is protected
tells you the same.
Your second example is valid because you can use references to the base class of derived classes. In this case no constructor is called, a reference only refers to an existing object. Here is an example how can use std::ostream& to the std::cout:
#include <iostream>
int main() {
std::ostream& os = std::cout;
os << "something ..." << std::endl;
}
The reason behind using std::ostream& in overload of operator<< is that you may don't want to overload the the mentioned operator for all individual stream types, but only for the common base class of them which has the << functionality.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With