thespeedracer38

Height using Operator Overloading of >> and <<

Feb 4th, 2019
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.61 KB | None | 0 0
  1. /** Height program has been edited to facilitate
  2.     adding two objects of Height class using operator
  3.     overloading. << and >> have also been overloaded.
  4. */
  5.  
  6. #include <iostream>
  7. #include <cstdlib>
  8.  
  9. using namespace std;
  10.  
  11.  
  12. class Height{
  13.     int meter, centi_meter;
  14. public:
  15.     inline Height();
  16.     inline Height(int ,int);
  17.     inline Height(const Height&);
  18.     inline ~Height();
  19.     inline Height operator +(Height&);
  20.     friend istream& operator >>(istream&, Height&);
  21.     friend ostream& operator <<(ostream&, Height&);
  22. };
  23.  
  24. istream& operator >>(istream &in, Height &obj){
  25.     cout << "Meter = ";
  26.     in >> obj.meter;
  27.     cout << "Cetimeter = ";
  28.     in >> obj.centi_meter;
  29.     return in;
  30. }
  31.  
  32. ostream& operator <<(ostream &out, Height &obj){
  33.     out << obj.meter << "m " << obj.centi_meter << "cm" << endl;
  34.     return out;
  35. }
  36.  
  37. Height::Height(){
  38.     meter = 0;
  39.     centi_meter = 0;
  40. }
  41.  
  42. Height::Height(int meter, int centi_meter){
  43.     Height::meter = meter;
  44.     Height::centi_meter = centi_meter;
  45. }
  46.  
  47. Height::Height(const Height &copy){
  48.     meter = copy.meter;
  49.     centi_meter = copy.centi_meter;
  50. }
  51.  
  52. Height::~Height(){
  53.    
  54. }
  55.  
  56. Height Height::operator +(Height &height){
  57.     int c_m = (centi_meter + height.centi_meter) % 100;
  58.     int m = (meter + height.meter) + ((centi_meter + height.centi_meter) / 100);
  59.     return Height(m, c_m);
  60. }
  61.  
  62. int main() {
  63.     system("cls");
  64.     Height obj1, obj2;
  65.     cout << "Enter the first height" << endl;
  66.     cin >> obj1;
  67.     cout << "Enter the second height" << endl;
  68.     cin >> obj2;
  69.     Height result = obj1 + obj2;
  70.     cout << " ";
  71.     cout << obj1;
  72.     cout << "+";
  73.     cout << obj2;
  74.     cout << "=";
  75.     cout << result;
  76.     cin.ignore();
  77.     cin.get();
  78.     return 0;
  79. }
Add Comment
Please, Sign In to add comment