#include <iostream> #include <math.h> using namespace std; //Another implementation of a complex number, this time as a class. class complex_number { //The members listed under public are accessible both inside and outside of //the class. public: //The following are two examples of a constructor. They are called //when an instance of the object is created. //1) This syntax is one way to initialize variables: complex_number(float re, float im) : real_part(re), imag_part(im) {}; //2) This is another, functionally equivalent, example of a constructor // complex_number(float re, float im) { // real_part = re; // imag_part = im; // }; //This is a destructor. It is called when the object is about to "die" ~complex_number() {}; //Some simple methods to set and get the real and imaginary parts void SetRealPart(float re) {real_part = re;}; void SetImagPart(float im) {imag_part = im;}; float GetRealPart() {return real_part;}; float GetImagPart() {return imag_part;}; //Some methods to calculate useful quantities of complex numbers float GetMagnitude() { return sqrt( pow(real_part,2) + pow(imag_part,2) ); }; float GetArgument() { return atan2( imag_part , real_part ) * 180.0 / M_PI; }; //This is an example of how we can overload the "+" operator to //implement addition of complex numbers. complex_number operator + (complex_number param) { float real_out = real_part + param.real_part; float imag_out = imag_part + param.imag_part; complex_number z_out(real_out,imag_out); return z_out; } //Only functions within the class have access to these private members. private: float real_part; float imag_part; }; //The main block gives some examples of how we might use this class. main() { complex_number z1(1.,1.); complex_number z2(-1.,0.); cout << "Number 1 is " << z1.GetRealPart() << " + i" << z1.GetImagPart() << endl; cout << "Magnitude 1 is " << z1.GetMagnitude() << endl; cout << "Argument 1 is " << z1.GetArgument() << endl; cout << "Number 2 is " << z2.GetRealPart() << " + i" << z2.GetImagPart() << endl; cout << "Magnitude 2 is " << z2.GetMagnitude() << endl; cout << "Argument 2 is " << z2.GetArgument() << endl; complex_number z3 = z1 + z2; cout << "Sum is " << z3.GetRealPart() << " + i" << z3.GetImagPart() << endl; cout << "Magnitude of sum is " << z3.GetMagnitude() << endl; cout << "Argument of sum is " << z3.GetArgument() << endl; }