Reputation: 1
class Book
{
string title;
int category;
public:
Book(const string& abook, int num);
string getTitle() const;
int getCategory() const;
friend ostream& operator<<(ostream& os, const Book& abook);
friend istream& operator>>(istream& is, Book& abook);
};
class Reader // base class
{
private:
string reader_name;
vector<Book> bookLists;
public:
string showname() const;
void add(const Book& abook); // organize book list
friend ostream& operator<<(ostream& os, const Reader& read_name);
friend istream& operator>>(istream& is, Reader& read_name);
};
class fantasyReader : public Reader { };
class horrorReader : public Reader { };
class scienceReader : public Reader { } ;
class mysteryReader : public Reader { };
I have two given text files.
1) Reader.txt <--- contains reader's name and category
For ex.
David <- reader's name
0 <- david is Fantasy reader
2) Book.txt <---- contains Book's title and category
For ex
Riddick <- Book's title
0 <- Book's category is fantasy
In the main function, array of pointers to Reader's obj are pointing each dervied class;
ex
Reader *obj[10];
int pos =0;
obj[pos++] = new fantasyReader();
The main goal is to organize book's list and put into a appropriate category and appropriate reader
and write them into a new text file.
ex.
-David-
Riddick
-John-
The Crow
MY QUESTION
I'm not sure what should be inside of operator<< and operator>>
for class Book and class Reader
Upvotes: 0
Views: 473
Reputation: 206508
What should you put inside the overloaded << and >> operators?
Well, You can actually put anything inside the overloaded <<
and >>
operator. They will just be simple function calls whenever a appropriate opportunity presents.
For eg:
Book obj;
cout<< obj; //Calls your overloaded << operator
As a general principle while overloading operators you should follow Principle of Least Astonishment, which means your code should be doing something similar what the operator does for a intrinsic data type. In the above example I would expect my <<
operator to display the contents of my Book
class, in that case I would overload it as follows:
// Display title and category
ostream& operator<<(ostream& os, const Book& abook);
{
os << abook.title << "\n";
os << abook.category<< "\n";
return os; // must return ostream object
}
I need to return a stream object since it allows for the chaining
ex:
Book obj1,obj2,obj3;
cout<<obj1<<obj2<<obj3;
Similarly, for >>
Extraction operator I would expect the operator to get the data from user.
For ex:
Book obj;
cin>>obj; //Calls your overloaded >> operator
I would overload the >>
operator as follows:
//Get the Book Title & Category from User
istream& operator>>(istream& is, Book& abook)
{
cout << "Enter Book Title: ";
is >> abook.title ;
cout << "Enter Book Category: ";
is >> abook.category;
return is; //Must return stream object
}
So, the bottomline is You can put any functionality inside >>
and <<
operators but don't forget the Principle of Least Astonishment!
Upvotes: 6