#include<iostream> #include<algorithm> #include<string> #include<stdexcept> using namespace std; enum Type{Int,Dou,Str}; class Any { private: void *ptr; Type type; public: Any(); ~Any(); Any operator=(int x); Any operator=(double x); Any operator=(string x); operator int(); operator double(); operator string(); }; Any::Any() { ptr=0; } Any::~Any() { // ptr; } Any Any::operator =(int x) { if(ptr!=0) { switch(type) { case Int: delete (int*)ptr; break; case Dou: delete (double*)ptr; break; case Str: delete (string*)ptr; break; } } ptr=new int(x); type=Int; } Any Any::operator =(double x) { if(ptr!=0) { switch(type) { case Int: delete (int*)ptr; break; case Dou: delete (double*)ptr; break; case Str: delete (string*)ptr; break; } } ptr=new double(x); type=Dou; } Any Any::operator =(string x) { if(ptr!=0) { switch(type) { case Int: delete (int*)ptr; break; case Dou: delete (double*)ptr; break; case Str: delete (string*)ptr; break; } } ptr=new string(x); type=Str; } Any::operator int() { if(type!=Int) throw logic_error("it's not a integer!"); else return *((int*)ptr); } Any::operator double() { if(type!=Dou) throw logic_error("it's not a integer!"); else return *((double*)ptr); } Any::operator string() { if(type!=Str) throw logic_error("it's not a integer!"); else return *((string*)ptr); } int main() { Any one; one=4.55; cout<<(double)one<<endl; one=400; cout<<(int)one<<endl; one=string("world"); cout<<(string)one<<endl; try { cout<<(int)one<<endl; } catch(logic_error err) { cout<<err.what()<<endl; } Any *ptr=&one; delete ptr; return 0; }