“实体”类的运算符=无法正常工作

时间:2016-11-17 15:53:41

标签: c++ operator-overloading entity

好的,所以我正在创建自己的实体组件系统,我希望能够将实体设置为另一个,这是它的外观:

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也会被设置:

'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

我认为问题可能是我使用指针“实体”而不是常规的“实体”,但我无法改变它。

2 个答案:

答案 0 :(得分:2)

这里的问题是你试图返回对局部变量的引用。在您的作业运算符中,您有

return Entity(this->Name, this->Tag, true, this->IsStatic);

这会创建一个临时的。你不能通过引用返回它。

您想要做的是返回对您刚刚分配给的对象的引用。你用

做到了
return *this;

请注意,代码leshko = ent2;中的指针赋值不是对象赋值。如果要分配基础对象,则需要*leshko = *ent2;

答案 1 :(得分:1)

您的operator=只需返回this

Entity& operator=(const Entity& other) {
    this->Name = other.Name;
    this->Tag = other.Tag;
    this->IsStatic = other.IsStatic;
    return *this;
}

毕竟,*this是您刚刚分配的内容,而=运算符的结果是对*this的引用。