Advertisement
TheWhiteFang

Tutorial 7 Q2 [Member Function method]

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