How to add new function to cout by using operator overloading

The results:

No. : 1
Deadline : 3
Cost : 4

As we all know, the cout is an ostream operator that could print the data type that has already be written in the default setting. But sometimes, we need to construct some new data structure to satisfy our demands. At this time, if you would like to cout the data structure you just created, the compiler will not permit you to do that. 

Now, the operator overloading just comefrom the hearven to help you to address the problem you just faced 

The codes:

// how to finish the assignments in the lowest cost.
# include <iostream>
# include <iomanip>
# include <algorithm>
using namespace std;
struct assignment_details{
    int No;
    int Deadline; // to illustrate the deadlines of every assignment
    int Cost;      // the cost of miss the deadline of every assignment
    bool operator< (const assignment_details& other) const { 
        if (Cost == other.Cost) 
            return Deadline < other.Deadline; // if the cost of the assignment are same, sort them by increaing   
        else 
            return Cost > other.Cost;     // if the cost of the assignment are different, sort them by decreaing
    }
    assignment_details(int no, int deadline, int cost){
        No = no; Deadline = deadline; Cost = cost;
    }
};
ostream& operator<< (ostream& COUT, assignment_details& assigment){
    COUT << "No. : " << assigment.No << endl;
    COUT << "Deadline : " << assigment.Deadline << endl;
    COUT << "Cost : " << assigment.Cost << endl;
    return COUT;
}
int main()
{
    assignment_details assigment1(1, 3, 4);
    cout << assigment1 << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_38396940/article/details/120931423