#include<iostream>
#include<exception>
using namespace std;
#include<vector>
#include<fstream>
#include<sstream>
#include<new>
class Array
{
public:
Array();
Array(const Array& src);
virtual ~Array();
virtual Array & operator =(const Array & rValue);
virtual int & operator [](int index);
virtual int &operator*();
//virtual const string &operator*()const;//const version
virtual Array* operator->();
virtual operator void *()const;//convert Object to pointer;
virtual operator bool()const;//convert Object to bool;
virtual bool operator !()const;
virtual void test()
{
cout<<"to test operator->()"<<endl;
}
protected:
int *mArray;
int mSize;
string mMsg;
const static int defaultSize=10;
};
Array::Array():mSize(defaultSize)
{
mMsg=" ";
try{
mArray=new int[mSize];
}catch(bad_alloc &e)
{
cerr<<"allocate memery failed!"<<endl;
exit(1);
}
catch(...)
{
cerr<<"other exception!"<<endl;
exit(1);
}
}
Array::~Array()
{
delete [] mArray;
}
Array::Array(const Array& src)
{ int i;
mSize=src.mSize;
mMsg=src.mMsg;
mArray=new int [mSize];
for( i=0;i<mSize;i++)
{
mArray[i]=src.mArray[i];
}
}
Array & Array::operator =(const Array & rValue)
{ if(this!=&rValue)
{
int i;
mSize=rValue.mSize;mMsg=rValue.mMsg;
delete []mArray;
mArray=new int [mSize];
for(i=0;i<mSize;i++)
{
mArray[i]=rValue.mArray[i];
}
}
return (*this);
}
int & Array::operator[](int index)
{
return mArray[index];
}
int & Array::operator*()
{
return (*mArray);
}
Array * Array::operator->()
{
return (this);
}
Array::operator void *()const
{
return mArray;
}
Array::operator bool()const
{
return (mArray!=NULL);
}
bool Array::operator !()const
{
return (mArray!=NULL?true:false);
}
void main()
{
Array object;
int i;
for(i=0;i<10;i++)
{
object[i]=i;
}
for(i=0;i<10;i++)
{
cout<<object[i]<<" ";
}
cout<<endl;
*object=123;
cout<<*object<<endl;
object->test();
//在没有重载bool和void*转化操作符下面的对对象的操作是不能编译通过的随便哪一个版本都能让下面的代码编译通过
if(object!=NULL)
{
cout<<"not null"<<endl;
}
if(object)
{
cout<<"not null"<<endl;
}
//重载!操作符
if(!object)
{
cout<<"not object"<<endl;
}else
{
cout<<"created object"<<endl;
}
}