简体   繁体   中英

istream >> ostream << Operator Overloading with * Pointer

How would I overload the >> and << operators if they are dealing with pointers?

in header:

friend std::istream& operator >>( std::istream& ins, Classname* & e);
friend std::ostream& operator <<( std::ostream& outs, const Classname * e);

in cpp:

std::ostream& operator <<( std::ostream& outs, const Classname * e)
{   // what do I do here?
return outs;
}
std::istream& operator >>( std::istream& ins, Classname* & e){
// what do I do here?
    return ins;
}

It depends on what is in the class Classname . If for example you have:

class Classname {
//...
private:
  int a;
};

.. then you might do:

std::ostream& operator <<( std::ostream& outs, const Classname * e)
{  
  outs << e->a;
  return outs;
}
std::istream& operator >>( std::istream& ins, Classname* & e){
    ins >> e->a;
    return ins;
}

The idea being that the << and >> operators ideally should mirror each other - so for example you can make use of them for serializing and deserializing your instances.

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