Example:7
Define an equal to relational operator function named operator ==() that can be used to compare two date class objects having data members as day, month and year.
Sol:
// to overload == operator // to compare two date classes(day,month,year) objects #include<iostream> #include<conio.h> using namespace std; class date { private: int day,month,year; public: date(); date(int d,int m,int y); void get(); void disp(); int operator==(date d); }; date::date() { day=0;month=0;year=0; } date::date(int d,int m,int y) { day=d;month=m;year=y; } void date::get() { cout<<"Enter date(day,month and year) "; cin>>day>>month>>year; } void date::disp() { cout<<"day "<<day<<" month "<<month<<" year "<<year<<endl; } int date::operator==(date d) { if (day==d.day && month==d.month && year==d.year) return(1); else return(0); } int main() { date s1,s2; s1.get();s2.get(); s1.disp();s2.disp(); int t; t=s1==s2; //t=s1.operator==(s2); if (t==1) cout<<"Both the dates are same"<<endl; else cout<<"Date are not same"<<endl; getch(); return(0); }
Output:
Enter date(day,month and year) 10 2 2021
Enter date(day,month and year) 10 2 2021
day 10 month 2 year 2021
day 10 month 2 year 2021
Both the dates are same
Example:8
Declare a class named time with attributes as hh,mm and ss. Take input for two objects and compare them using overloaded “==” operator.
Sol:
code
Output: