[英]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.