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 Object-oriented programming A Function on Complex Numbers | ||
A Function on Complex Numbers
Let's look at some of the operations we might want to perform on complex numbers. The absolute value of a complex number is defined to be sqrt(x2 + y2). The abs function is a pure function that computes the absolute value. Written as a nonmember function, it looks like this: // nonmember functiondouble abs (Complex c) { return sqrt (c.real * c.real + c.imag * c.imag); }
{ private: double real, image; public: // ...constructors // member function double abs () { return sqrt (real*real + imag*imag); } }; I removed the unnecessary parameter to indicate that this is a member function. Inside the function, I can refer to the instance variables real and imag by name without having to specify an object. C++ knows implicitly that I am referring to the instance variables of the current object. If I wanted to make it explicit, I could have used the keyword this: class Complex{ private: double real, image; public: // ...constructors // member function double abs () { return sqrt (this->real * this->real + this->imag * this->imag); } }; But that would be longer and not really any clearer. To invoke this function, we invoke it on an object, for example Complex y (3.0, 4.0);double result = y.abs ();
|
||
Home Object-oriented programming A Function on Complex Numbers |