美文网首页
组合模式 C++实现

组合模式 C++实现

作者: 假程序员 | 来源:发表于2019-04-17 00:40 被阅读0次
    //
    //  main.cpp
    //  composite_pattern
    //
    //  Created by apple on 2019/4/16.
    //  Copyright © 2019年 apple. All rights reserved.
    //
    
    #include <iostream>
    #include "list"
    #include "string"
    using namespace std;
    
    
    class Composite
    {
    private:
        string name;
        list<Composite *> composites;
    public:
        Composite(string name) {this->name =  name;}
        void add_composite(Composite *composite)
        {
            composites.push_back(composite);
        }
        list<Composite *> get_Composites()
        {
            return composites;
        }
        void print_Name() {cout<<name<<endl;}
        ~Composite()
        {
            for (list<Composite *>::iterator item = composites.begin(); item != composites.end(); ++item)
            {
                delete *item;
                *item = NULL;
            }
            composites.clear();
        }
    };
    
    int main(int argc, const char * argv[]) {
        Composite *composite = new Composite("姓名簿");
        composite->add_composite(new Composite("张三"));
        composite->add_composite(new Composite("李四"));
        composite->add_composite(new Composite("王五"));
        composite->add_composite(new Composite("陈六"));
        composite->print_Name();
        list<Composite *> composites = composite->get_Composites();
        for (list<Composite *>::iterator item = composites.begin(); item != composites.end(); ++item)
        {
            (*item)->print_Name();
        }
        delete composite;
        return 0;
    }
    
    姓名簿
    张三
    李四
    王五
    陈六
    Program ended with exit code: 0
    

    相关文章

      网友评论

          本文标题:组合模式 C++实现

          本文链接:https://www.haomeiwen.com/subject/nzmwwqtx.html