C++友元类,工厂模式和继承的融合案例

//友元没有继承性,没有传递性,所以在animal中定义友元类是无效的
    class animal{
    public:
        animal(){};
        virtual ~animal(){};
    };

    class Cat:public animal
    {
        friend class animalFactory;
    private:
        Cat(){
        }

    private:
        string m_name;
        string m_color;

    public:
        void about()
        {
            cout<<"my name is "<<m_name<<",my color is "<<m_color<<endl;
        }
        ~Cat() override{

        }
    };

    class Dog:public animal{
        friend  class animalFactory;
    private:
        Dog()
        {
        }

    private:
        string m_name;
        string m_color;
        int m_age;

    public:
        ~Dog() override{

        }

        void about() const{
            cout<<"i am a dog,my name is "<<m_name<<",my color is"<<m_color<<",i am "<<m_age<<"years old"<<endl;
        }
    };

    class animalFactory{
    public:
        static animal* createCat(string name,string color)
        {
            Cat* p_cat=new Cat;
            p_cat->m_color=color;
            p_cat->m_name=name;
            return p_cat;
        }
    public:
        static animal* createdog(string name,string color,int age){
            Dog* p_dog=new Dog;
            p_dog->m_name=name;
            p_dog->m_color=color;
            p_dog->m_age=age;
            return p_dog;
        }
    };

    void friend_test(){
        animal* cat=animalFactory::createCat("cat","black");
        Cat* real_cat=dynamic_cast<Cat*>(cat);
        real_cat->about();

        animal* dog=animalFactory::createdog("dog","white",1);
        Dog* real_dog=dynamic_cast<Dog*>(dog);
        real_dog->about();
    }
    //运行结果如下:
  //my name is cat,my color is black
//i am a dog,my name is dog,my color iswhite,i am 1years old
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值