实现一个功能类似Any的类
2010-11-09 09:50
344 查看
#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; }
相关文章推荐
- 扩展 delphi 泛型 以实现类似lambda功能 , C#中的any count first last 等扩展方法
- JavaWeb实现同一帐号同一时间只能一个地点登陆(类似QQ登录的功能)
- 最近做了一个类似社交的网站,看到新浪微博右侧有一个网页在线聊天的功能,如何才能实现网页在线聊天功能(新浪微博这种聊天)?
- 匹配输入华为:编程实现联想输入法 输入联想功能是非常实用的一个功能,请编程实现类似功能
- java web中实现同一帐号同一时间只能一个地点登陆(类似QQ登录的功能)
- 如何实现一个类似与电子口令卡的密码验证的功能
- 使用jQuery实现一个类似GridView的编辑,更新,取消和删除的功能
- 使用jQuery实现一个类似GridView的编辑,更新,取消和删除的功能
- 实现一个简单类似linux上cat命令的功能函数
- java web中实现同一帐号同一时间只能一个地点登陆(类似QQ登录的功能)
- 扩展 delphi 泛型 以实现类似lambda功能 , C#中的any count first last 等扩展方法
- java web中实现同一帐号同一时间只能一个地点登陆(类似QQ登录的功能)
- java web中实现同一帐号同一时间只能一个地点登陆(类似QQ登录的功能)
- 【Unity快速实现小功能】实现一个类似跑马灯的效果
- java web中实现同一帐号同一时间只能一个地点登陆(类似QQ登录的功能)
- java web中实现同一帐号同一时间只能一个地点登陆(类似QQ登录的功能)
- 当我们想点击一个链接实现删除或者类似的功能,想给出一个提示,具体实现方法
- (转)使用一个下拉框或文本框+列表框的方式实现类似IE地址栏自动完成的功能
- 用C语言写一个数组,实现类似JAVA语言中ArrayList的功能
- 请写一个函数,实现类似的strcpy的字符串复制功能