PageRenderTime 37ms CodeModel.GetById 12ms app.highlight 20ms RepoModel.GetById 1ms app.codeStats 0ms

/downcast/ch01/main.cpp

https://github.com/jinjianxin/My-Program
C++ | 117 lines | 98 code | 18 blank | 1 comment | 13 complexity | 5fcae3da6a371700af4859671752077b MD5 | raw file
  1#include <vector>
  2#include <iostream>
  3
  4
  5using namespace std;
  6
  7class  Security
  8{
  9	protected:
 10		enum { BASEID = 0};
 11	public:
 12		virtual ~Security() {};
 13		virtual bool isA(int id) {return (id == BASEID);}
 14};
 15
 16class Stock : public Security
 17{
 18	typedef Security Super;
 19	protected:
 20	enum {OFFECT = 1,TYPEID = BASEID+OFFECT};
 21	public:
 22	bool isA(int id)
 23	{
 24		return id == TYPEID || Super::isA(id);
 25	}
 26
 27	static Stock *dynacast(Security *s)
 28	{
 29		return (s->isA(TYPEID))? static_cast<Stock *>(s):0;
 30	}
 31};
 32
 33class Bond : public Security
 34{
 35	typedef Security Super;
 36	protected:
 37	enum {OFFECT = 2,TYPEID = BASEID+OFFECT};
 38	public:
 39	bool isA(int id)
 40	{
 41		return id == TYPEID || Super::isA(id);
 42	}
 43
 44	static Bond *dynacast(Security *s)
 45	{
 46		return (s->isA(TYPEID))? static_cast<Bond *>(s):0;
 47	}
 48};
 49
 50class Investment : public Security
 51{
 52	typedef Security Super;
 53	protected:
 54	enum {OFFECT = 3,TYPEID = BASEID+OFFECT};
 55	public:
 56	bool isA(int id)
 57	{
 58		return id == TYPEID || Super::isA(id);
 59	}
 60
 61	static Investment *dynacast(Security *s)
 62	{
 63		return (s->isA(TYPEID))? static_cast<Investment *>(s):0;
 64	}
 65
 66	void special()
 67	{
 68		cout<<"special Investment function"<<endl;
 69	}
 70};
 71
 72class Metal : public Investment
 73{
 74	typedef Security Super;
 75	protected:
 76	enum {OFFECT = 4,TYPEID = BASEID+OFFECT};
 77	public:
 78	bool isA(int id)
 79	{
 80		return id == TYPEID || Super::isA(id);
 81	}
 82
 83	static Metal *dynacast(Security *s)
 84	{
 85		return (s->isA(TYPEID))? static_cast<Metal *>(s):0;
 86	}
 87};
 88
 89int main(int argc,char *argv[])
 90{
 91	vector<Security *> portfolio;
 92
 93	portfolio.push_back(new Metal);
 94	portfolio.push_back(new Investment);
 95	portfolio.push_back(new Bond);
 96	portfolio.push_back(new Stock);
 97
 98	for(vector<Security*>::iterator it = portfolio.begin();it !=portfolio.end();++it)
 99	{
100//		Investment *cm = Investment::dynacast(*it);
101		Investment *cm = dynamic_cast<Investment *>(*it);
102		if(cm)
103			cm->special();
104		else
105			cout<<"not an Investment"<<endl;
106	}
107
108	Security *sp = new Metal;
109	Investment *cp = Investment::dynacast(sp);
110	if(cp)
111		cout<<"it's an Investment"<<endl;
112
113	Metal *mp = Metal::dynacast(sp);
114	if(mp)
115		cout<<"it's a Metal too!"<<endl;
116
117}