Advertisement
TheWhiteFang

Tutorial 7 Q2 [Top-level method]

Dec 7th, 2014
275
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.27 KB | None | 0 0
  1. // http://pastebin.com/u/TheWhiteFang
  2. #include <iostream>
  3.  
  4. using namespace std;
  5.  
  6. class ComplexNum{
  7.     float m_Real;
  8.     float m_Img;
  9. public:
  10.     ComplexNum(float inReal=0.0 , float inImg=0.0){// To be completed
  11.    
  12.         m_Real = inReal;
  13.         m_Img = inImg;
  14.     }
  15.  
  16. friend ComplexNum operator* (const ComplexNum &inVal1, const ComplexNum &inVal2);
  17. friend ostream &operator<<(ostream &output, const ComplexNum &source);
  18. };
  19.  
  20. //top level function
  21. ComplexNum operator* (const ComplexNum &inVal1, const ComplexNum &inVal2)
  22. {
  23.     ComplexNum temp;
  24.     temp.m_Real = (inVal1.m_Real * inVal2.m_Real)-(inVal1.m_Img * inVal2.m_Img);
  25.     temp.m_Img = (inVal1.m_Real * inVal2.m_Img) + (inVal1.m_Img * inVal2.m_Real);
  26.    
  27.    
  28.     return temp;
  29.  
  30. }
  31.  
  32. //top level global to overload stream operator
  33. ostream &operator<<(ostream &output, const ComplexNum &source){ //return ostream by reference //only thing that changes is classname
  34.     output << source.m_Real << " + " << source.m_Img << "i " <<endl;
  35.     return output;
  36. }
  37.  
  38.  
  39. int main(){
  40.     ComplexNum obj1(10.5, 20.8);
  41.     ComplexNum obj2(31.8, 23.6);
  42.     cout<< "Complex Num 1: " << obj1 << endl;
  43.     cout<< "Complex Num 2: " << obj2 << endl;
  44.  
  45.     ComplexNum obj3;
  46.     obj3 = obj1 * obj2;
  47.     cout <<endl <<"Complex Num 1 × Complex Num 2 = ";
  48.     cout << obj3 << endl;
  49.     return 0;
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement