C++ Standard Library C++ STL Library

C++ <complex> - operator= Function



The C++ complex::operator= function supports assignment operator of two complex numbers or a complex and a scalar.

Syntax

complex& operator= (const T& val);
complex& operator= (const complex& rhs);
template<class X> complex& operator= (const complex<X>& rhs);

Parameters

val Specify scalar value of matching type.
rhs Specify complex value of matching type.

Return Value

*this.

Example:

In the example below, the complex::operator= function is used to perform assignment operation on a given complex number.

#include <iostream>
#include <complex>
using namespace std;
 
int main (){
  complex<double> z1 (10, 20);
  complex<double> z2 (2, 3);
  double x = 0.5;
  
  //displaying z1
  cout<<"z1 : "<<z1<<"\n";
   
  //assigned z2 to z1
  z1 = z2;

  //displaying z1
  cout<<"z1 : "<<z1<<"\n";  

  //assigned x to z1
  z1 = x;

  //displaying z1
  cout<<"z1 : "<<z1<<"\n";  

  return 0;
}

The output of the above code will be:

z1 : (10,20)
z1 : (2,3)
z1 : (0.5,0)

❮ C++ <complex> Library