简体   繁体   中英

Cannot overload operator because cannot access private member declared in class

I have a class with an operator overload as so:

friend ostream operator<< (ostream &stream, const Item &item){
          stream << item.title << " - " << item.format << " (Loaned to " << item.name << ") on " << item.date;
          return stream;
    }

My program fails to compile and gives me the following error:

error C2248: 'std::basic_ios<_Elem,_Traits>::basic_ios' : cannot access private member declared in class 'std::basic_ios<_Elem,_Traits>'
1>        with
1>        [
1>            _Elem=char,
1>            _Traits=std::char_traits<char>
1>        ]
1>        c:\program files (x86)\microsoft visual studio 8\vc\include\ios(151) : see declaration of 'std::basic_ios<_Elem,_Traits>::basic_ios'
1>        with
1>        [
1>            _Elem=char,
1>            _Traits=std::char_traits<char>
1>        ]
1>        This diagnostic occurred in the compiler generated function 'std::basic_ostream<_Elem,_Traits>::basic_ostream(const std::basic_ostream<_Elem,_Traits> &)'
1>        with
1>        [
1>            _Elem=char,
1>            _Traits=std::char_traits<char>
1>        ]

What is going on? Why is it saying that a private member cannot be access, I am confused.

You have to return a reference.

friend ostream& operator<< (ostream &stream, const Item &item)
//            ^

The copy-constructor of streams is deleted/private.

The problem is with:

friend ostream operator<< (ostream &stream, const Item &item){

You need to return the stream by reference, ostream objects are not copyable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM