您的位置:首页 > 其它

实现一个功能类似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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐