读书人

用C++实现的装饰者模式遇到有关问题

发布时间: 2012-02-25 10:01:48 作者: rapoo

用C++实现的装饰者模式,遇到问题,
没有到达装饰者模式的目的,目的是类Person,装饰类Decorator,具体类有两个分别是头发和鞋子,想用头发和鞋子来装饰Person,显示鞋子,头发,但是结果只显示了头发,请大家指点。。。

C/C++ code
#include <iostream>#include <string>using namespace std;class Person{private:    string name;public:    Person()     {    }    Person(string name)    {        this->name=name;    }    virtual void show()    {        cout<<" Decorator name "<<name<<endl;    }};class Decorator:public Person{protected:    Person component;public:    void Deco(Person component)    {        this->component=component;    }    void show()    {        component.show();    }};class toufa:public Decorator{public:    void show()    {        cout<<"头发"<<endl;        component.show();    }};class shoot:public Decorator{public:    void show()    {        cout<<"鞋子"<<endl;        component.show();        }};int main(){    Person fuli("fuli");    //shoot *xie= new shoot();    //toufa *tou= new toufa();    shoot xie;    toufa tou;    //xie->Deco(fuli);    //tou->Deco(*xie);    //tou->show();    xie.Deco(fuli);    tou.Deco(xie);    tou.show();    return 0;}



[解决办法]
用指针吧,用父类复制的时候会有切割问题
C/C++ code
class Person{private:    string name;public:    Person()    {    }    Person(string name)    {        this->name=name;    }    virtual void show()    {        cout<<" Decorator name "<<name<<endl;    }};class Decorator:public Person{protected:    Person* component;public:    void Deco(Person *component)    {        this->component=component;    }    void show()    {        component->show();    }};class toufa:public Decorator{public:    void show()    {        cout<<"头发"<<endl;        component->show();    }};class shoot:public Decorator{public:    void show()    {        cout<<"鞋子"<<endl;        component->show();    }};int main(){    Person fuli("fuli");    shoot xie;    toufa tou;    xie.Deco(&fuli);    tou.Deco(&xie);    tou.show();    return 0;} 

读书人网 >C++

热点推荐