// Exercise about classes: implementation of complex numbers.
// Note modifiers like const and static can be used
// ONLY for functions that are memebrs of a class.
// Also, they cannot be used for constructors.
#include <iostream>
#include <cmath>
using namespace std;
class complex
{
public:
float x,y;
complex();
complex(float x1, float y1);
complex add(complex a, complex b) const;
float magnitude(complex a) const;
};
int main()
{
float m, n;
// complex c3(); // ERROR
complex c3;
cout << "Enter the real part of the first complex "
<< "number followed by the imaginary part:\n";
cin >> m >> n;
complex c1(m,n);
cout << "Enter the real part of the second complex "
<< "number followed by the imaginary part:\n";
cin >> m >> n;
complex c2(m,n);
c3 = c3.add(c1,c2);
// c3 = c1.add(c1,c2); // OK
// c1 = c1.add(c1,c2); // OK
cout << "The sum of the two numbers is: "
<< c3.x << " + " << c3.y << " i.\n";
cout << "The magnitude/length of the first is: "
<< c1.magnitude(c1) << endl;
cout << "The magnitude/length of the second is: "
<< c2.magnitude(c2) << endl;
return 0;
}
complex::complex()
{
x = 0; y = 0;
}
complex::complex(float x1, float y1)
{
x = x1; y = y1;
}
complex complex::add(complex a, complex b) const
{
complex sum;
sum.x = a.x + b.x;
sum.y = a.y + b.y;
return sum;
}
float complex::magnitude(complex a) const
{
return sqrt(a.x * a.x + a.y * a.y);
}