The C++Course provides a general introduction to programming in C++. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details. 
Home Objectoriented programming Complex Numbers  
Complex Numbers
Continuing the example from the previous chapter, we will consider a class definition for complex numbers. Complex numbers are useful for many branches of mathematics and engineering, and many computations are performed using complex arithmetic. A complex number is the sum of a real part and an imaginary part, and is usually written in the form x + yi, where x is the real part, y is the imaginary part, and i represents the square root of 1. Thus, i · i = 1.
{ private: double real, imag; public: Complex () { real = 0.0; imag = 0.0; } Complex (double r, double i) { real = r; imag = i; } }; There should be nothing surprising here. The instance variables are two doubles that contain the real and imaginary parts. The two constructors are the usual kind: one takes no parameters and assigns default values to the instance variables, the other takes parameters that are identical to the instance variables. In main, or anywhere else we want to create Complex objects, we have the option of creating the object and then setting the instance variables, or doing both at the same time: Complex x;x.real = 1.0; x.imag = 2.0; Complex y (3.0, 4.0);


Home Objectoriented programming Complex Numbers 