C++ have native suport for integer and real numbers, but not for complex numbers. All operations must be implemented or we should use the library <complex>.
I'm having problem in pass a complex number, as complex number and not to real numbers, into a class.
When I want to pass a complex number to a function, using the header <complex>, I do:
return result;
}
and it works! But what I want is to store a complex number inside of a class! For this I define a class "parameters". For doubles, ints, etc, it's easy, but with complex numbers I don't know how to do it.
Here it's an example of what I want to do (but doesn't work).
//File with name parameters.h
#ifndef PARAMETERS_H
#define PARAMETERS_H
//typedef complex<double> dcmplx;
class parameters
{
public: parameters(); //constructor
//Simulation parameters
complex<double> variable;
private:
};
#endif
and
//File with name parameters.cpp
#include "Parameters.h"
#include <iostream>
#include <complex>
#include <cmath>
using namespace std;
//Initialization of the constructor
parameters::parameters()
{
//Constants of the system
variable = (2.0,3.0);
}
Can anyone help me? I'm desperate!!! I'm thinking in go back to fortran!!!
In c++ the expression (2.0 ,3.0) simply ignores the 2.0 and uses only the right most value (3.0).
The best way to initialise your complex number is in the ctor-initializer. After the constructor function name and parameter list you can put a comma separated list if initialisations after a colon:
#include <complex>
class parameters
{
public:
parameters(); //constructor
//Simulation parameters
std::complex<double> variable;
private:
};
parameters::parameters()
: variable(2.0, 3.0) // initialize here in the ctor-initializer
{
//... not here
}
parameters.h:20: error: ISO C++ forbids declaration of ‘complex’ with no type
parameters.h:20: error: invalid use of ‘::’
parameters.h:20: error: expected ‘;’ before ‘<’ token
parameters.cpp: In constructor ‘parameters::parameters()’:
parameters.cpp:15: error: class ‘parameters’ does not have any field named ‘variable’
nuno@toshiba-ubuntu:~/Research/ICMM/DDA_program/tests$