Storing a reference to the calling object

drug drug2004 at bk.ru
Sat May 23 09:43:03 UTC 2020


23.05.2020 12:27, Tim пишет:
> class Sprite{
>      /// Postional components of the sprite
>      int* x, y;
>      SDL_Surface* image_surface;
>      auto parent;
> 
>      this(const char* path, auto parent){
>          writeln(*x);
>          this.parent = parent;
>      }
> 
>      void update(){
>          // Copy loaded image to window surface
>          writeln("Sprites x: ",  *x);
>          SDL_Rect dstRect;
>          dstRect.x = parent.x;
>          dstRect.y = parent.y;
>          SDL_BlitSurface(image_surface, null, g_surface, &dstRect);
>      }
> }

You can make the Sprite class templated one:
```
class Sprite(T){
     /// Postional components of the sprite
     int* x, y;
     SDL_Surface* image_surface;
     T parent;

     this(const char* path, T parent){
         writeln(*x);
         this.parent = parent;
     }

     void update(){
         // Copy loaded image to window surface
         writeln("Sprites x: ",  *x);
         SDL_Rect dstRect;
         dstRect.x = parent.x;
         dstRect.y = parent.y;
         SDL_BlitSurface(image_surface, null, g_surface, &dstRect);
     }
}

auto sprite(T)(const char* path, T parent)
{
	return new Sprite!T(path, parent);
}
```
and use it like:
```
auto sprite = sprite(path, this);
```


More information about the Digitalmars-d-learn mailing list