【发布时间】:2016-11-17 15:53:41
【问题描述】:
好的,所以我正在制作自己的实体组件系统,并且我希望能够将一个实体设置为另一个,这是它的外观:
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
我认为问题可能在于我使用的是指针“实体”而不是常规的“实体”,但我无法更改。
【问题讨论】:
-
推荐阅读What is the copy-and-swap idiom?,这通常是更好的方法
operator=。 -
“我试过你们告诉我的,我是这样尝试的:”谁让你这么做的?我在任何地方都没有看到它。
-
@LightnessRacesinOrbit 好的,我很确定用户:NathanOliver 和 Sam Varshavchik 建议我使用“return *this”,如果我错了,请纠正我。
-
他们从未指示您重写代码以在任何地方使用动态分配。在你的“我是这样尝试的”修改代码 sn-p 中没有
return *this。 -
“我认为问题可能在于我使用的是指针‘实体’而不是常规‘实体’,但我无法改变它。”不,你不是’ t 使用指针'实体'(但现在你是)。这个问题我很困惑,你也是!
标签: c++ operator-overloading entity