Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Complex Arithmetic Without Complexities-4 : Page 4




Application Security Testing: An Integral Part of DevOps

Arithmetic Operations
One of the advantages of using <complex> is the set of built-in operators that it overloads for you. The overloaded unary operators are:

//binary + template <class T> complex<T> operator+ (const complex<T>&, const complex<T>&); template <class T> complex<T> operator+ (const complex<T>&, const T&); template <class T> complex<T> operator+ (const T&, const complex<T>&); //..similar overloads for -, *, /, == and != //unary + and – template <class T> complex<T> operator+ (const complex<T>&); template <class T> complex<T> operator- (const complex<T>&);

These overload sets allow you to combine complex objects with native floating point variables in the same expression:

complex <double> val(2,2), val2(-11.2,3); val = val2 + 9.99; //operator+(complex,double) cout<<val<<endl; // (-1.21,3) val2 -= 0.7; cout<<val2<<endl; // (-11.9,3)

When you add a floating point value to a complex object, that value is added to the real part whereas the imaginary part remains intact.

Getting real
The C++ Standard defines at least two methods for accessing the real and imaginary parts of a complex number. The first method uses the member functions real() and imag():

complex <double> compnum(5.9, -2.15); double x=compnum.imag(); //x equals -2.15 double y=compnum.real();// y equals 5.9

Alternatively, use the template functions std::real() and std::image() extract the real and imaginary parts of a complex object:

x=std::imag (compnum); y=std::real(compnum);

Here's how you modify the real or imaginary parts:

compnum.real(5.5); compnum.imag(-5.59);

Simple and Efficient
The <complex> library is a classic example of the advantages of a standardized, generic solution to a recurring programming task. It's simple enough to allow users to master it easily and pretty efficient because it makes no use of inheritance or virtual functions.

Danny Kalev is a certified system analyst and software engineer specializing in C++. He was a member of the C++ standards committee between 1997 and 2000 and has since been involved informally in the C++0x standardization process. He is the author of "The ANSI/ISO Professional C++ Programmer's Handbook" and "The Informit C++ Reference Guide: Techniques, Insight, and Practical Advice on C++."
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date