灵巧指针(smartpointer)的类型转换
#include <iostream.h>
template<class X> class auto_ptr
{
public:
typedef X element_type;
explicit auto_ptr(X* p = 0) throw(): the_p(p) {}
auto_ptr(auto_ptr<X>& a) throw(): the_p(a.release()){}
auto_ptr<X>& operator =(auto_ptr<X>& rhs) throw()
{
reset(rhs.release());
return *this;
}
~auto_ptr() throw() {delete the_p;}
X& operator* () const throw() {return *the_p;}
X* operator-> () const throw() {return the_p;}
X* get () const throw() {return the_p;}
X* release() throw()
{
X* tmp = the_p;
the_p = 0;
return tmp;
}
void reset(X* p = 0) throw()
{
if (the_p!=p)
{
delete the_p;
the_p = p;
}
}
// 模板成员函数为了实现类型转换
template<class Other> operator auto_ptr<Other> () throw( )
{
return ato_ptr<Other>(*this);
}
private:
X* the_p;
};
class A{
public:
A(int i=1):x(i){}
int x;
};
class B: public A
{
public:
B(int j=2):y(j){}
int y;
};
void display(auto_ptr<A>& a)
{
cout<<a->x<<endl;
}
int main( )
{
auto_ptr<A> a(new A());
auto_ptr<B> b(new B());
display(b);//为什么这一步总是出错?????
return 0;
}