I implemented a class for auto pointer.
It seems that I can NOT override an operator<< in this class?
The complier reports:
Code:
main.cc:18: warning: friend declaration `std::ostream&
operator<<(std::ostream&, const AutoPtr<T>&)' declares a non-template
function
main.cc:18: warning: (if this is not what you intended, make sure the function
template has already been declared and add <> after the function name here)
-Wno-non-template-friend disables this warning
Here is the code:
Code:
template <typename T>
class AutoPtr{
private:
T* ptr;
public:
AutoPtr(T* p=0);
~AutoPtr();
AutoPtr(AutoPtr<T>& rhs);
AutoPtr<T>& operator = (AutoPtr<T>& rhs);
T operator*() const;
T* operator->() const;
friend ostream& operator<<(ostream& os, const AutoPtr<T>& obj); //Error here.
};
template <typename T>
ostream&
operator<<(ostream& os, const AutoPtr<T>& obj){
if (obj.ptr)
os<<*(obj.ptr)<<endl;
else
os<<"<NULL>"<<endl;
return os;
}
template <typename T>
AutoPtr<T>::AutoPtr(T* p):ptr(p){}
template <typename T>
AutoPtr<T>::~AutoPtr(){
delete(ptr);
}
template <typename T>
AutoPtr<T>::AutoPtr(AutoPtr<T>& rhs){
ptr = rhs.ptr;
rhs.ptr=0;
}
template <typename T>
AutoPtr<T>&
AutoPtr<T>::operator=(AutoPtr<T>& rhs){
if(this != &rhs){
this->ptr = rhs.ptr;
rhs.ptr=0;
}
return (*this);
}
template <typename T>
T
AutoPtr<T>::operator*()const{
return *ptr;
}
template <typename T>
T*
AutoPtr<T>::operator->()const{
return ptr;
}
int main(){
AutoPtr<int> ptr;
cout<<ptr;
AutoPtr<int> ptr2(new int(100));
cout<<ptr2;
/*
ptr(ptr2);
cout<<ptr;
cout<<ptr2;
AutoPtr<int> ptr3;
ptr3 = ptr;
cout<<ptr;
cout<<ptr3;
*/
return 0;
}