'std::ios_base::ios_base(const std::ios_base&)’ is private' error while overloading operator<< for std::ostram
Solution 1
std::ostream
is not copy constructible, and when you return by value you are copy constructing. Although return value optimization means the copy might not actually be made, the compiler still requires that copying be possible.
The canonical return value for this operator is by non-const reference:
std::ostream& operator<<(std::ostream& o, const SomeType& t);
Solution 2
Return by reference:
std::ostream& operator<<(...)
//^
Otherwise an attempt is being made to copy s
, and ostream
s are non-copyable (the error message is stating an attempt to access a private
copy constructor).
Solution 3
You forgot reference in return type:
std::ostream &operator<<(std::ostream & s, person & os)
{
return s << os.surname;
}
Kacper Kołodziej
I'm student of Computer Science at Łódź University of Technology (Poland). I'm interested in C++, Python, Linux and embedded systems. I write about programming on my devblog in Polish and English
Updated on June 17, 2022Comments
-
Kacper Kołodziej almost 2 years
I've got a struct which looks like this:
sturct person { string surname; person(string n) : surname(n) {}; }
I need to overload
operator<<
forstd::ostream
andperson
. I wrote this function:std::ostream operator<<(std::ostream & s, person & os) { s << os.surname; return s; }
but I receive this errors:
/usr/include/c++/4.6/bits/ios_base.h|788|error: ‘std::ios_base::ios_base(const std::ios_base&)’ is private|
/usr/include/c++/4.6/bits/basic_ios.h|64|error: within this context
/usr/include/c++/4.6/ostream|57|note: synthesized method ‘std::basic_ios::basic_ios(const std::basic_ios&)’ first required here |
-
Jarrod Cabalzar over 10 yearsThanks for that, helped me out :) +1