程序设计实习实验班2017作业(神奇的MyAny 作业14)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
#include <iostream> #include <vector> #include <string> #include <typeinfo> using namespace std; class MyClass { public: int n; MyClass(int m):n(m) { } void f() { cout << n << " func." << endl; } }; class MyAny{ public: class base{ public: virtual ~base(){} }; template<class T> class V :public base{ public: T* v; V(const T &_v){ v = new T(_v); } ~V(){ delete v; } }; base *content; template <class T> MyAny(const T &_v):content(new V<T>(_v)){} ~MyAny(){ } }; template <class T> T MyAny_cast(const MyAny& m) { return *(static_cast < MyAny::V<T>* > (m.content))->v; } template <class T> T* MyAny_cast(MyAny* m) { MyAny::V<T> *p; p = (dynamic_cast < MyAny::V<T>* > (m->content)); if(!p)return NULL; return p->v; } int main() { while(true) { int n; string s; cin >> n >> s; if ( n == 0) break; MyAny a = n; cout << MyAny_cast<int>(a) << endl; a = s; cout << MyAny_cast<string>(a) << endl; a = MyClass(n+1); MyAny b = n + 2; MyAny * p = new MyAny(MyClass(n+3)); MyAny c = MyClass(n+4); c = * p; b = * p; delete p; MyAny d = b; MyAny_cast<MyClass>(&a)->f(); MyAny_cast<MyClass>(&b)->f(); MyAny_cast<MyClass>(&c)->f(); MyAny_cast<MyClass>(&d)->f(); c = s + "OK"; cout << MyAny_cast<string>(c) << endl; int * pi = MyAny_cast<int> ( & c); if( pi == NULL) cout << "not a int" << endl; else cout << "the int is " << * pi << endl; string * ps = MyAny_cast<string> ( & c); if( ps == NULL) cout << "not a string" << endl; else cout << "the string is " << * ps << endl; } } |
Subscribe