Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // http://pastebin.com/u/TheWhiteFang
- // Tutorial 7 Q1 [Top-Level method]
- #include <iostream>
- using namespace std;
- class Distance{ //by default, member variables are private
- int m_Kilometre;
- int m_Metre;
- int m_Centimetre;
- public:
- Distance(double inVal = 0.0) //both a default or parametrized constructor //need to add for temp to work
- {
- //inval =2.5359
- m_Kilometre = (int)inVal;
- m_Metre = (inVal - (double)m_Kilometre)*1000.0; //(2.539 -2)*1000 = 535 //double casting and .0 to avoid ambiguity in compiler
- m_Centimetre = (((inVal - (double)m_Kilometre) * 1000.0) - m_Metre) * 100;
- } //constructor
- friend Distance operator+ (const Distance &inVal1, const Distance &inVal2);
- friend ostream &operator<<(ostream &output, const Distance &source);
- };
- //top level function needs to be global
- Distance operator+ (const Distance &inVal1, const Distance &inVal2)
- {
- Distance temp;
- temp.m_Centimetre = inVal1.m_Centimetre + inVal2.m_Centimetre;
- if(temp.m_Centimetre >=100){
- temp.m_Metre++;
- temp.m_Centimetre = temp.m_Centimetre - 100;
- }
- temp.m_Metre += inVal1.m_Metre + inVal2.m_Metre;//+= to add present value of temp.m_metre
- if(temp.m_Metre >=1000){
- temp.m_Kilometre++;
- temp.m_Metre = temp.m_Metre - 1000;
- }
- temp.m_Kilometre += inVal1.m_Kilometre + inVal2.m_Kilometre; //+= will add original value instead of overwriting
- return temp; //temp will be stored in val3
- }
- //top level global function
- ostream &operator<<(ostream &output, const Distance &source){ //return ostream by reference //only thing that changes is classname
- output << source.m_Kilometre << "km " << source.m_Metre << "m " << "and " << source.m_Centimetre <<"cm "<<endl;
- return output;
- }
- int main()
- {
- Distance val1(2.5359);
- Distance val2(3.7769);
- Distance val3;
- cout<< "Value 1 is: " << val1 << endl;
- cout<< "Value 2 is: " << val2 << endl << endl;
- val3 = val1 + val2;
- cout << val1 << " + " << val2 << " = " << val3<< endl;
- cout << endl << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement