【问题标题】:Operator= of class 'Entity' doesn't work properly'Entity' 类的 Operator= 无法正常工作
【发布时间】: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


【解决方案1】:

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

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

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

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

return *this;

请注意,在您的代码中leshko = ent2; 是指针分配而不是对象分配。如果你想分配你需要的底层对象*leshko = *ent2;

【讨论】:

  • 成功了,我用整数做了一些测试,知道这是指针赋值,但不知道如何解决,谢谢。
【解决方案2】:

您的operator= 只需返回this

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

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

【讨论】:

  • 是的,我第一次就是这样,然后我把它改成了那里显示的那个,它不起作用。
猜你喜欢
  • 1970-01-01
  • 2020-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-01
  • 1970-01-01
  • 2013-11-20
相关资源
最近更新 更多