Classes in D and C++

Andy Little andy at servocomm.freeserve.co.uk
Mon Mar 5 02:02:45 PST 2007


Lionello Lunesu Wrote:

> Instead of a constructor, create a "static opCall". opCall is the 
> overload for "(..)" so you can instantiate your type similar to C++:
> 
> struct SomeType {
>    int member = 0;// default initializer here
>    static SomeType opCall( int whatever ) {
>      SomeType st;
>      st.member = whatever;//custom initialize
>      return st;
>    }
>    //...
> }
> 
> SomeType st = 2;//construction
> 
> No need for constructors ;)

Aha. If I chnge struct to class I am getting something close to what I want:
import std.stdio;
class X{
 
      static X opCall( double n )
      {
         X xx;
         xx.x = n;
         return xx;
      }

private:
   double x;
}


int main(char[][] args)
{
  X x = X(3); //ok
//###############
  X x = 3; // lError ine 21
  //#############
 X y = x; // OK
   writefln("%s",x.x);
   return 0;
}

gives:

class1.d(21): Error: cannot implicitly convert expression (3) of type int to cla
ss1.X
Error: cannot cast int to class1.X
(Which is what I want :-) )
That sorts that case out. 

I'm back on the road for the moment :-)

regards
Andy Little







More information about the Digitalmars-d mailing list