HackerRank C++ Overload Operators




You are given a class - Complex.

class Complex
{
public:
int a,b;
};
Operators are overloaded by means of operator functions, which are regular functions with special names. Their name begins with the operator keyword followed by the operator sign that is overloaded. The syntax is:

type operator sign (parameters) { /*... body ...*/ }
You need to overload operators + and << for the Complex class.



  1. //Operator Overloading
  2. #include<iostream>
  3. using namespace std;
  4. class Complex
  5. {
  6. public:
  7. int a,b;
  8. void input(string s)
  9. {
  10. int v1=0;
  11. int i=0;
  12. while(s[i]!='+')
  13. {
  14. v1=v1*10+s[i]-'0';
  15. i++;
  16. }
  17. while(s[i]==' ' || s[i]=='+'||s[i]=='i')
  18. {
  19. i++;
  20. }
  21. int v2=0;
  22. while(i<s.length())
  23. {
  24. v2=v2*10+s[i]-'0';
  25. i++;
  26. }
  27. a=v1;
  28. b=v2;
  29. }
  30. };
  31. //Overload operators + and << for the class complex
  32. //+ should add two complex numbers as (a+ib) + (c+id) = (a+c) + i(b+d)
  33. //<< should print a complex number in the format "a+ib"
  34. Complex operator+(const Complex & X, const Complex & Y) {
  35. Complex Z {X.a + Y.a, X.b + Y.b};
  36. return Z;
  37. }
  38. ostream & operator<< (ostream & out, const Complex & X) {
  39. if (X.b < 0) {
  40. out << X.a << "-i" << -X.b;
  41. } else if(X.b > 0) {
  42. out << X.a << "+i" << X.b;
  43. } else {
  44. out << X.a;
  45. }
  46. return out;
  47. }
  48. int main()
  49. {
  50. Complex x,y;
  51. string s1,s2;
  52. cin>>s1;
  53. cin>>s2;
  54. x.input(s1);
  55. y.input(s2);
  56. Complex z=x+y;
  57. cout<<z<<endl;
  58. }
Please click on the like button if it worked

Solution not working or have any suggestions? Please send an email to [email protected]


donate a cup of tea :)


Join Our Facebook Group

Share this solution






codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube