<fa*************@free.fr> wrote in message
news:11**********************@u72g2000cwu.googlegr oups.com...
The proper way to define streaming operators is:
ostream& operator << ( ostream& s, MyClass const& obj ) { ... }
istream& operator >> ( istream& s, MyClass& obj ) { ... }
They are non-member functions. [ NB: both have to "return s;" ]
But you can declare them within the class, as friends, if
these functions need access to private members:
friend ostream& operator << ( ostream& s, MyClass const& obj );
friend istream& operator >> ( istream& s, MyClass& obj );
I know these but do not see how to implement things in the aim to be
used like this :
obj i;
cin >> i; // <- How to prepare the job for this ?
cout << *i.eval( top_env ) << '\n';
I wanted to be able to write the read of different kind of objects (
nil, symbol, cons, proc ) this simple way.
You just input them. I do this quite a bit in my program, I'll try to show
a rather simple example.
This one is not simple but I'll cut out a lot of stuff just so you get the
idea. So it may not compile as is.
class CHealth
{
public:
// Snipped - Not needed for example
private:
// Lot of other stuff snipped here
int OverallMax_; int Overall_;
int HeadMax_;
int Head_;
int TorsoMax_;
int Torso_;
int LeftArmMax_;
int LeftArm_;
int RightArmMax_;
int RightArm_;
int LeftLegMax_;
int LeftLeg_;
int RightLegMax_;
int RightLeg_;
int LeftWingMax_;
int LeftWing_;
int RightWingMax_;
int RightWing_;
};
std::istream& operator>>( std::istream& is, CHealth& Health)
{
is >> Health.OverallMax_ >> Health.Overall_ >> Health.HeadMax_ >>
Health.Head_ >> Health.TorsoMax_ >> Health.Torso_ >>
Health.LeftArmMax_ >> Health.LeftArm_ >> Health.RightArmMax_ >>
Health.RightArm_ >>
Health.LeftLegMax_ >> Health.LeftLeg_ >> Health.RightLegMax_ >>
Health.RightLeg_ >>
Health.LeftWingMax_ >> Health.LeftWing_ >> Health.RightWingMax_ >>
Health.RightWing_;
// Snipped checking of some values and setting values in class that were
also snipped,
// such as Dead_, LeftArmDisabled_, etc...
return is;
}
std::ostream& operator<<( std::ostream& os, CHealth& Health)
{
os << Health.OverallMax_ << " " << Health.Overall_ << " " <<
Health.HeadMax_ << " " << Health.Head_ << " " <<
Health.TorsoMax_ << " " << Health.Torso_ << " " <<
Health.LeftArmMax_ << " " << Health.LeftArm_ << " " <<
Health.RightArmMax_ << " " << Health.RightArm_ << " " <<
Health.LeftLegMax_ << " " << Health.LeftLeg_ << " " <<
Health.RightLegMax_ << " " << Health.RightLeg_ << " " <<
Health.LeftWingMax_ << " " << Health.LeftWing_ << " " <<
Health.RightWingMax_ << " " << Health.RightWing_;
return os;
}