Complex number question
-
I have an application that uses complex numbers. From an example I have clipped some supposedly working code that includes a complex number definition:
@
double re;
double im;
complex(double r = 0.0, double i = 0.0) : re(r), im(i) { }
@yet I can find no documentation to explain this to me. This may be a newbie question but what does the colon after the complex number do? Qt complains that line 3 does not name a type. I thought complex WAS a type when <complex> is included?!
What am I missing / doing wrong?
-
This is a basic C++ question. The : in line 3 above initializes the re and the im variables to r and i respectively on construction of complex.
-
Why then does the compiler complain about it not having a type?
-
FWIW here is a quick example/addition to what Andre said.
@
class base
{
public:
virtual ~base() {}
};class derived : public base
{
unsigned Value;
public:
derived(unsigned val) : Value(val) {}
};int main(int argc, const char *argv[])
{
derived myDerived(0);return 0;
}
@ -
bq.
double re;
double im;
complex(double r = 0.0, double i = 0.0) : re(r), im(i) { }the compiler is complaining because what you are doing is conflicting with what the compiler do automatically.It is called the defaulf constructor and it should be provided with no arguments.
try this instead
@
double re;
double im;
complex() : re(0.0), im(0.0) { }
complex(double r ,double i) : re(r),im(i) {}
@If you want to initialize you variables to 0 default constructor is the correct way.I guess you were trying to do just that.and you can also do it like this
@
double re;
double im;
complex() {re=0.0;im=0.0; }
complex (double r, double i) {re=r;im=i;}
@ -
Found it! The example I clipped the code from used ambigous terms calling the redefinition the same as the class. So I renamed the new one m_complex every where it is used and all is well with the compiler.
-
your code just like a class definition
3.complex(double r = 0.0, double i = 0.0) : re( r ), im(i) { }
this is a constructor of class complex,so if you want to use class complex,just declare it:
complex mycomplex;
or complex mycomplex(0.12, 0.56);