samedi 19 août 2017

One line initialization of class who's values are set with a method instead of the constructor

Say I have a class Test:

class Test {
public:
  int a;

  Test();
  int set(int a);
};

Test::Test() {}

int Test::set(int a) {
  this->a = a;
  return a;
}

An instance of this class would be able to be initialized with a value like this (of course):

Test t;
t.set(10);

But is there a way to do this in one line? The following code doesn't work.

Test t.set(10);


When would I want to do this?

I'm using a game development library - SFML - and to apply a texture to a shape I need to pass a reference to a Texture instance, like this:

Texture texture;
texture.loadFromFile("mud.png");

rect.setTexture(&texture);

And I want to create a class with some static constants defining some textures, which I could then use elsewhere.

Aucun commentaire:

Enregistrer un commentaire