C++ complex real


The C++ complex real function compute the real part of the complex number.There are three overloaded version of ‘real’ functions.The declaration of the three functions is shown below.

1 constexpr T real( ) const;
2 void real(T val);
3 template<class T> constexpr T real(const complex< T >& x);

The first two are member functions but the third one is non-member function.A detail description of each of this function is given below.



constexpr T real( ) const;

The sole purpose of this function is to get the real value of the complex number.

Parameters:
none

Return type
T -The real value of the complex number.The ‘T’ is the type of the object.

Code example

complex< double > c1(12.45e2 , 123.091);

cout<< c1.real() << endl ;

complex< int > cI(575 , 999);

cout<< cI.real() << endl ;

Output,

12.45e2
575

Note the real value returned by this function can be assigned directly to any complex number of the same type.In doing so the real value of the complex number on the left side is changed to the real value returned by the function.

Code example

complex< double > cc(23 , 21.56) , cc1( 1 , 0.9) ;

cc1=cc.real(); //real value of cc1 is changes to 23

cout<< cc1.real() ;

Output,

23

Direct assignment of any real value to complex object is allowed since the complex class support the ‘operator=(T)’ function.This operator allows direct assignment of any values to the complex object invariably.And in the line ‘cc1=cc.real();‘ this operator function is called.


 




void real(T val);

The sole purpose of this function is to change the real value of the complex number if the need ever arises.

Parameters:
val :The new value of the real number belonging to the object type.

Return type
none

Code example

complex< double > c1(456.7 , 2.3);

cout<< c1.real() << endl ;

c1.real( 2990.33 ); //change real value of c1 to 2990.33

cout<< c1.real() << endl ;

complex< int > cI(0 , 0);

cI.real( 1000 ); //change real value of cI to 1000

cout<< cI.real() << endl ;

Output,

456.7
2990.33
1000



template<class T> complex< T > real(const complex< T >& x);

This functions also returns a real number of the complex number.This function is similar in all ways to the first ‘real’ function except it is non-member function.

Parameters:
Complex number -A complex number whose real value is to be accessed.

Return type
template<class T> -The returned value is either ‘x.real()’ or a complex number of the form (x.real() , 0) if the return value is assigned to a complex object.Note the imaginary part is always 0.

Link :C++ complex imag()

Code example

complex<long double > c1(2.342 , 9.02) , c2(34 , 90) ;

cout<< real( c1 ) ;

c2=real( c1 ) ;

cout<< c2.real( ) << endl
<< c2.imag( ) ; //access the imaginary value of c2

Output ,

2.342
2.342
0

c2 initial imaginary value is 90 but after the line ‘c2=real( c1 ) ;’ the imaginary value of c2 is overwritten by the value 0.