标签:
#include <IOSTREAM> #include <STRING> #include<vector> using namespace std; class Component{ public: Component(const string & str):name(str){} virtual void add(Component * p) = 0; virtual void display(int depth) = 0; string name; }; class Leaf:public Component{ public: Leaf(const string & str):Component(str){} void add(Component * p){ cout<<"the leaf cant add a component"<<endl; } void display(int depth){ string str; int i = 0; for( i =0;i<depth;i++){ str+=" "; } str+=this->name; cout<<str<<endl; } }; class Composite:public Component{ public: Composite(const string & str):Component(str){} void add(Component * p ){ m_compsite.push_back(p); } void display(int depth){ //层级显示,对vector中的成员依次当为Composite调用各自的display int i = 0; string str; for(i = 0;i<depth;i++){ str+=" "; } str+=this->name; cout<<str<<endl; vector<Component *>::iterator it= m_compsite.begin(); for(;it!=m_compsite.end();it++){ (*it)->display(depth+1); } } private: vector<Component *> m_compsite; }; int main(int argc, char* argv[]) { Composite * p = new Composite("总公司"); Composite * pchild1 = new Composite("子公司1"); Composite * pchild2 = new Composite("子公司2"); Composite * pchild1child = new Composite("子公司1的子公司"); Leaf * pworker = new Leaf("小王"); //最后的叶子,已经不可再add成员了 pchild1child->add(pworker); pchild1->add(pchild1child); p->add(pchild1); p->add(pchild2); p->display(0); return 0; }
标签:
原文地址:http://www.cnblogs.com/xiumukediao/p/4636463.html