Advertisement
TheWhiteFang

Tutorial 7 Q1 [Top-Level method]

Dec 7th, 2014
294
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.01 KB | None | 0 0
  1. // http://pastebin.com/u/TheWhiteFang
  2. // Tutorial 7 Q1 [Top-Level method]
  3. #include <iostream>
  4. using namespace std;
  5.  
  6. class Distance{ //by default, member variables are private
  7.  
  8.     int m_Kilometre;
  9.     int m_Metre;
  10.     int m_Centimetre;
  11.  
  12. public:
  13.  
  14.     Distance(double inVal = 0.0) //both a default or parametrized constructor  //need to add for temp to work
  15.     {
  16.    
  17.         //inval =2.5359
  18.         m_Kilometre = (int)inVal;
  19.         m_Metre = (inVal - (double)m_Kilometre)*1000.0; //(2.539 -2)*1000 = 535 //double casting and .0 to avoid ambiguity in compiler
  20.         m_Centimetre = (((inVal - (double)m_Kilometre) * 1000.0) - m_Metre) * 100;
  21.    
  22.    
  23.    
  24.    
  25.     } //constructor
  26.     friend Distance operator+ (const Distance &inVal1, const Distance &inVal2);
  27.     friend ostream &operator<<(ostream &output, const Distance &source);
  28. };
  29.  
  30. //top level function needs to be global
  31.  
  32. Distance operator+ (const Distance &inVal1, const Distance &inVal2)
  33. {
  34.     Distance temp;
  35.     temp.m_Centimetre = inVal1.m_Centimetre + inVal2.m_Centimetre;
  36.    
  37.     if(temp.m_Centimetre >=100){
  38.         temp.m_Metre++;
  39.         temp.m_Centimetre = temp.m_Centimetre - 100;
  40.     }
  41.  
  42.     temp.m_Metre += inVal1.m_Metre + inVal2.m_Metre;//+= to add present value of temp.m_metre
  43.     if(temp.m_Metre >=1000){
  44.         temp.m_Kilometre++;
  45.         temp.m_Metre = temp.m_Metre - 1000;
  46.     }
  47.  
  48.     temp.m_Kilometre += inVal1.m_Kilometre + inVal2.m_Kilometre; //+= will add original value instead of overwriting
  49.     return temp; //temp will be stored in val3
  50. }
  51.  
  52. //top level global function
  53. ostream &operator<<(ostream &output, const Distance &source){ //return ostream by reference //only thing that changes is classname
  54.     output << source.m_Kilometre << "km " << source.m_Metre << "m " << "and " << source.m_Centimetre <<"cm "<<endl;
  55.     return output;
  56. }
  57.  
  58.  
  59. int main()
  60. {
  61.     Distance val1(2.5359);
  62.     Distance val2(3.7769);
  63.     Distance val3;
  64.  
  65.     cout<< "Value 1 is: " << val1 << endl;
  66.     cout<< "Value 2 is: " << val2 << endl << endl;
  67.     val3 = val1 + val2;
  68.     cout << val1 << " + " << val2 << " = " << val3<< endl;
  69.     cout << endl << endl;
  70.  
  71.     return 0;
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement