Search code examples
c++complex-numbers

Problem with assigning values to complex variables using real() and imag()


I want to assign a value (here 0.0f) to a complex variable which I defined first using std::complex<float>. The real and imaginary part of the variable should be then assigned using real(...)=0.0f and imag(...)=0.0f. But by compiling I get the error "lvalue required as left operand of assignment". I tried g++ 7.5 and also 6.5 and I got this error from both.

temp = new float[ nfft ];
  tempComplex = new std::complex< float >[ nf ];
  if ( processing->getComponentNSToProc() ) {
for ( int i = 0; i < sampNum; i++ ) {
  temp[ i ] = srcData[ iSrc ].rcvData[ iRcv ].dataNS[ i ];
  qDebug() << "before: temp[" << i << "] =" << temp[ i ] << "; ....dataNS[" << i << "] =" << srcData[ iSrc ].rcvData[ iRcv ].dataNS[ i ] << ";";
}
for ( int i = sampNum; i < nfft; i++ ) {
  temp[ i ] = 0.0f;
  qDebug() << "before: temp[" << i << "] =" << temp[ i ] << ";";
}
for ( int i = 0; i < nf; i++ ) {
  real( tempComplex[ i ] ) = 0.0f;
  imag( tempComplex[ i ] ) = 0.0f;

Solution

  • For using a non-static member function of a class we need to use(call) it through an object of that class. So you can change your code to look like:

    int main() 
    {
        
      std::complex<float> *tempComplex = new std::complex< float >[ 3];
      
      for ( int i = 0; i < 3; i++ ) 
      {
          
          tempComplex[i].real(0.0f);
          
          tempComplex[i].imag(0.0f);
          std::cout<<tempComplex[i]<<std::endl;
       }
    }
    

    The above code now works because tempComplex[i] is an object and we access the non-static member function named real and imag of the class std::complext<float>through this(tempComplex[i]) object.

    Also after everything(at appropriate point) don't forget to use delete.