c++ - Operator= of class 'Entity' doesn't work properly -
okay i'm making own entity component system, , want able set entity another, here how looks:
entity& operator=(const entity& other) { this->name = other.name; this->tag = other.tag; this->isstatic = other.isstatic; return entity(this->name, this->tag, true, this->isstatic); }
an entity has id has unique other entities, when set entity another, id gets set:
'main.cpp' entity = entity("a", "tag of a"); // automatically gets id: 0 because first entity created entity b = entity("b", "tag of b"); // b gets id: 1 because second entity created a.printall(); // function prints name, tag, , id of entity, prints out: " "a" has "tag of a" tag, , id = "0" " // after set b, things little messy = b; a.printall(); // prints out: " "b" has "tag of b" tag, , id = "1" ", should not happen, why did id of change ?
the way ids work when entity constructed id set global variable increments 1, so:
'public.h' // included everywhere, has global variables int idcounter = 0; int getnewid(){ return idcounter; idcounter++; }
and inside entity constructor:
'entity.cpp' entity::entity(string name, string tag){ this->name = name; this->tag = tag; this->id = getnewid(); // fine, problem operator= }
edit:
i tried guys told me, here how tried it:
entity* leshko; entity* ent2; leshko = new entity("leshko", "lesh"); ent2 = new entity("ent2", "presh"); leshko->printall(); // id = 0 leshko = ent2; leshko->printall(); // id = 1
i think problem may i'm using pointer 'entities' , not regular 'entities', cannot change that.
the issue here trying return reference local variable. in assignment operator have
return entity(this->name, this->tag, true, this->isstatic);
which creates temporary. cannot return reference.
what want instead return reference object assigned to. with
return *this;
note in code leshko = ent2;
pointer assignment not object assignment. if want assign underlying objects need *leshko = *ent2;
.
Comments
Post a Comment