xml抽象

#include<iostream>
#include<vector>
#include<cstdio>
#include<string>
using namespace std;

class Content
{
    public: 
        string flag;    //用来区别Element类和Text类的标志
};

class Text: public Content
{
    private:
        string text;
    public :
        Text();
        Text(string text){this->text = text;}
        void getContent()
        { cout <<"the text is:"<< this->text<<endl; }
};

class Element : public Content
{
    private:
        string name; 
        vector<Content*> contents;
    public :
        Element();
        Element(string name){this->name = name;}
        void setElementName(string name){this->name = name;} 
        Element* addElement(string name);
        void addText(string text);    
        void getContent()
        {
            cout <<"the element's name is:"<<name<<endl;
        }
        void show();
};

Element* Element:: addElement(string name)
{
     Element *element =  new Element(name);
     element->flag = "Element";
     this->contents.push_back(element);
     return element;
}

void Element:: addText(string text)
{
    Text *t = new Text(text);
    t->flag = "Text";
    this->contents.push_back(t);
}

void Element:: show()
{
    
            int len =this->contents.size();
            this->getContent();
            for(int i=0;i<len;i++)
            {
                if(this->contents[i]->flag == "Element")
                {
                  Element *next =(Element *) this->contents[i];
                  next->show();
                 // ((Element)(this->contents[i])).show();
                }
                else
                {
                   Text *next = (Text *) this->contents[i];   //此处的转换,看了许久之后,才用了指针
                   next->getContent();
                 // ((Text)(this->contents[i])).getContent();
                }
            }
}

int main()
{
    Element *book = new Element("book");
    Element *title = book->addElement("title");
    title->addText("java");

    book->show();    
     
    return 0;
}

/*
* 最终的收获就是,类的强制类型转换,最好是用在指针上
* 人懒了,不想把各种类分成几个文件,久将就一下吧,况且这只是初稿中的初稿
*/

转载于:https://my.oschina.net/wanborj/blog/54026

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值