重载=运算符后,
const Warrior& Warrior::operator = (const Warrior& warriorObj)
{
if (this != &warriorObj)
{
name = warriorObj.name;
start = warriorObj.start;
alignment = warriorObj.alignment;
strength = warriorObj.strength;
craft = warriorObj.craft;
gold = warriorObj.gold;
life = warriorObj.life;
fate = warriorObj.fate;
specialAbility = warriorObj.specialAbility;
numberOfObjects = warriorObj.numberOfObjects;
}
return *this;
}
一旦我在驱动程序中创建了2个勇士:
Warrior *w1, *w2;
w1 = new Warrior();
w2 = new Warrior();
w1 = w2;
如果我更改
w1
的参数之一,它也会将w2
的参数更改为同一件事...我哪里做错了?
最佳答案
由于您正在分配指针,因此不会调用重载的运算符。您可以使用
*w1 = *w2;
或者更好的是,根本不使用动态对象:
Warrior w1, w2;
w1 = w2;
关于c++ - 运算符重载C++(=),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13591443/