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