How to use an istream in a class member function?
Hi,
I learn C++ from a C++ Primer book. I find its class header file having a member
function:
Sales_item(std::istream &is) { is >> *this; }
but I cannot find its application code to call it. I have tried myself, but it
fails because I uses file input stream does not match the std::istream type.
I do not know an appropriate input stream even after I see the inheritance map
of istream.
From this definition, it should be called.
Can you show me how to call this member function?
Thanks,
#include <iostream>
#include <string>
class Sales_item {
friend bool operator==(const Sales_item&, const Sales_item&);
// other members as before
public:
// added constructors to initialize from a string or an istream
Sales_item(const std::string &book):
isbn(book), units_sold(0), revenue(0.0) { }
Sales_item(std::istream &is) { is >> *this; }
friend std::istream& operator>>(std::istream&, Sales_item&);
friend std::ostream& operator<<(std::ostream&, const Sales_item&);
public:
// operations on Sales_item objects
// member binary operator: left-hand operand bound to implicit this pointer
Sales_item& operator+=(const Sales_item&);
// other members as before
public:
// operations on Sales_item objects
double avg_price() const;
bool same_isbn(const Sales_item &rhs) const
{ return isbn == rhs.isbn; }
// default constructor needed to initialize members of built-in type
Sales_item(): units_sold(0), revenue(0.0) { }
// private members as before
private:
std::string isbn;
unsigned units_sold;
double revenue;
};