欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

How to add new function to cout by using operator overloading

程序员文章站 2022-03-18 19:43:11
...

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;
}