2016-11-17 4 views
-1

オーケー動作しませんので、私は自分のエンティティコンポーネントシステムを作ってるんだ、と私はここでは、別のエンティティを設定できるようにしたい、それがどのように見えるかです:演算子は=クラスの「エンティティ」は正しく

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.cpp' 

Entity::Entity(string name, string tag){ 
this->name = name; 
this->tag = tag; 
this->ID = GetNewID(); // Everything fine, the problem is the operator= 
} 

EDIT:

Entity* leshko; 
Entity* ent2; 
leshko = new Entity("leshko", "lesh"); 
ent2 = new Entity("ent2", "presh"); 
leshko->PrintAll(); // ID = 0 
leshko = ent2; 
leshko->PrintAll(); // ID = 1 

私は思う:私は君たちが私に言ったことを試してみました

、ここで私はそれを試してみました方法です問題は、私がポインタ 'エンティティ'を使用しているのではなく、通常の 'エンティティ'を使用している可能性がありますが、私はそれを変更できません。

+0

よくあることは[コピーアンドスワップイディオムとは何ですか?](http://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom)を読むことをお勧めします。 'operator ='を使うより良い方法です。 – user4581301

+0

_ "私はあなたの人が私に言ったことを試しました、ここで私はそれを試した方法です:" _それをするように言った人は?私はどこにも見ない。 –

+0

@LightnessRacesinOrbit ok私はかなり確信しています:NathanOliverとSam Varshavchikは私が 'return * this'を使うことを提案しました、もし間違っていたら私を修正してください。 – kooldart

答えて

2

ここでの問題は、ローカル変数への参照を返そうとしていることです。あなたの代入演算子には

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

があります。これは一時的なものです。あなたはそれを参考として返すことはできません。

代わりにやりたいことは、割り当てられたオブジェクトへの参照を戻すことです。あなたは、あなたのコード内でleshko = ent2;割り当てを反対しないポインタ代入である注

return *this; 

であることがあることを行います。基礎となるオブジェクトを割り当てる場合は、*leshko = *ent2;が必要です。

+0

それは働いた、私は整数を使用していくつかのテストを行い、ポインタの割り当てだったが、それを修正する方法を知っていない、知っていた。 – kooldart

1

operator=は、単にthisを返す必要があります。結局のところ

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

*thisはあなただけに割り当てられたものであり、それは=オペレータ、*thisへの参照の結果です。

+0

はい、それは私が最初にそれを持っていた方法でした、そして、私はそこに表示されたものに変更しました、それは動作しません。 – kooldart