c++ overloading operator<< and>>

前端 未结 1 720
盖世英雄少女心
盖世英雄少女心 2021-01-17 04:22
class Book
{ 
     string title;
     int category;
 public:
    Book(const string& abook, int num);
    string getTitle() const;
    int getCategory() const;
           


        
相关标签:
1条回答
  • 2021-01-17 05:04

    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!

    0 讨论(0)
提交回复
热议问题