c++ create a class, call its funcion and push back to vector in one statement -


i have class myclass , class holds array of myclass, follows:

class myclass {     int a;     float b;      void setint(int value)     {         = value;     }      void setfloat(float value)     {         b = value;     } }  class myclassarray {     std::vector<myclass> classlist; } 

what easier way create new myclass, insert object in myclassarray , call methods store value on ?

can create temporary myclass , insert on vector, calling function in 1 statement ? like:

classlist.push_back(myclass().setint(21)); classlist.push_back(myclass().setfloat(1.23)); 

is valid ?

btw: need in vector 1 object myclass 21 set on a , 1 1.23 set on b, that´s why i´m not using initializers a , b.

you can use chaining :

class myclass {     int a;     float b; public:     myclass& set(int value)   { = value; return *this; }     myclass& set(float value) { b = value; return *this; } }; 

this enables thing like:

myclass a; a.set(1).set(1.5f); 

and also:

vector<myclass> vec; vec.push_back(myclass{}.set(3)); 

Comments

Popular posts from this blog

java - Spring Data JPA: Why findOne(id) executing delete query internally? -

python - Mongodb How to add addtional information when aggregating? -

java - Incorrect order of records in M-M relationship in hibernate -