[英]Operator= of class 'Entity' doesn't work properly
好的,所以我要创建自己的实体组件系统,并且希望能够将一个实体设置为另一个,如下所示:
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);
}
一个实体还具有一个ID,该ID必须与其他实体唯一,但是当我将一个实体设置为另一个实体时,该ID也会被设置:
'main.cpp'
Entity a = Entity("a", "tag of a"); // A automatically gets ID: 0 because its the first Entity created
Entity b = Entity("b", "tag of b"); // B gets ID: 1 because its the second Entity created
a.PrintAll(); // This is a function which prints the name, tag, and ID of an Entity, this prints out: " "a" has "tag of a" as a tag, and its ID = "0" "
// but after i set a to b, things get a little messy
a = b;
a.PrintAll(); // This now prints out: " "b" has "tag of b" as a tag, and its ID = "1" ", that should not happen, why did the ID of a change ?
ID的工作方式是,在构造实体时,将其ID设置为一个全局变量,该变量以1递增,如下所示:
'Public.h' // this is included everywhere, has all the global variables
int IDcounter = 0;
int GetNewID(){
return IDcounter;
IDcounter++;
}
然后在Entity构造函数中:
'Entity.cpp'
Entity::Entity(string name, string tag){
this->name = name;
this->tag = tag;
this->ID = GetNewID(); // Everything fine, the problem is the operator=
}
编辑:
我尝试了你们告诉我的方法,这是我尝试的方法:
Entity* leshko;
Entity* ent2;
leshko = new Entity("leshko", "lesh");
ent2 = new Entity("ent2", "presh");
leshko->PrintAll(); // ID = 0
leshko = ent2;
leshko->PrintAll(); // ID = 1
我认为问题可能在于我使用的是指针“实体”,而不是常规的“实体”,但是我无法更改它。
这里的问题是您试图返回对局部变量的引用。 在您的赋值运算符中
return Entity(this->Name, this->Tag, true, this->IsStatic);
这将创建一个临时文件。 您不能通过引用将其退回。
相反,您要做的是返回对您刚刚分配给的对象的引用。 你这样做
return *this;
注意,在您的代码中, leshko = ent2;
是指针分配而不是对象分配。 如果要分配基础对象,则需要*leshko = *ent2;
。
您的operator=
只需返回this
。
Entity& operator=(const Entity& other) {
this->Name = other.Name;
this->Tag = other.Tag;
this->IsStatic = other.IsStatic;
return *this;
}
毕竟, *this
是您刚分配的内容,而这是=
运算符的结果,它是对*this
的引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.