在练习装饰模式的时候编写了4个类
用相同的调用顺序,不同的调用方法
产生的结果不同
#include<iostream>
#include<memory>
using namespace std;
//抽象英雄
class AbstractHero {
public:
virtual void ShowStatus() = 0;
int mHP;
int mMP;
int mATK;
int mDF;
};
class HeroA :public AbstractHero {
public:
HeroA() {
mHP = 0;
mMP = 0;
mATK = 0;
mDF = 0;
}
virtual void ShowStatus() {
cout << "血量" << mHP << endl;
cout << "魔法" << mMP << endl;
cout << "攻击" << mATK << endl;
cout << "防御" << mDF << endl;
}
};
class AbstractEquipment :public AbstractHero {
public:
AbstractEquipment(AbstractHero* hero){
this->pHero = hero;
}
virtual void ShowStatus() = 0;
AbstractHero* pHero;
};
//狂徒
class KuanagTuEquipment :public AbstractEquipment {
public:
KuanagTuEquipment(AbstractHero* hero):AbstractEquipment(hero){}
void AddKuangtu() {
this->mHP = this->pHero->mHP + 1000;
this->mMP = this->pHero->mMP;
this->mATK = this->pHero->mATK;
this->mDF = this->pHero->mDF;
}
virtual void ShowStatus() {
AddKuangtu();
cout << "血量" << mHP << endl;
cout << "魔法" << mMP << endl;
cout << "攻击" << mATK << endl;
cout << "防御" << mDF << endl;
}
//增加额外功能
};
void test01() {
AbstractHero* hero = new HeroA;
hero->ShowStatus();
hero = new KuanagTuEquipment(hero);
hero->ShowStatus();
}
void test02() {
shared_ptr<AbstractHero> hero= make_shared<HeroA>();
hero->ShowStatus();
hero.reset(new KuanagTuEquipment(hero.get()));
hero.get()->ShowStatus();
}
int main() {
test01();
cout << endl;
test02();
}
就是想用KuanagTuEquipment 类更改HeroA对象的数值
test02()
函数中, 调用hero.reset()
后,hero
原来所指的对象就被销毁了,所以new KuanagTuEquipment(hero.get())
对象里所存的指针就变成了野指针。test01()
不存在这个问题,是因为你创建的两个对象都没有被销毁。