c++ - What does constructor do in this line? -


there simple code, found in c++ tutorial. can't understand line:

c1 = complex(10.0); 

in comments written constructor can used convert 1 type another. can explain moment. thank help.

#include <iostream> using namespace std;  class complex {   public:     complex() : dreal(0.0), dimag(0.0)     { cout << "invoke default constructor" << endl;}     /*explicit*/ complex(double _dreal)       : dreal(_dreal), dimag(0.0)     { cout << "invoke real constructor " << dreal <<endl;}     complex(double _dreal, double _dimag)       : dreal(_dreal), dimag(_dimag)     {         cout << "invoke complex constructor " << dreal              << ", " << dimag << endl;     }      double dreal;     double dimag; };  int main(int argcs, char* pargs[]) {     complex c1, c2(1.0), c3(1.0, 1.0);      // constructor can used convert 1 type     //     c1 = complex(10.0);      // following conversions work if explicit     // uncommented     c1 = (complex)20.0;     c1 = static_cast<complex>(30.0);      // following implicit conversions work if     // explicit commented out     c1 = 40.0;     c1 = 50;      system("pause");     return 0; } 

this right here:

complex(double _dreal)       : dreal(_dreal), dimag(0.0)     { cout << "invoke real constructor " << dreal <<endl;} 

is constructor take double , create complex object it. can see set real part (dreal) value passed constructor (_dreal), , setup imaginary part 0.

this line:

c1 = complex(10.0); 

will call constructor, , convert passed real number (10.0) complex object.

edit: please note not real conversion - explicitly creation of complex object passing double - have examples of conversions in answer provided dasblinkedlight.


Comments

Popular posts from this blog

c# - How Configure Devart dotConnect for SQLite Code First? -

java - Copying object fields -

c++ - Clear the memory after returning a vector in a function -