Today i will the example code of template class where i will show the assignment operator overloading ,deleteting the variable in safe mode.
#if !defined(_ARRAY_H)
#define P11_ARRAY_H
namespace MYARRAY {
template< class T > class CArray
{
public:
CArray() : m_data(0), m_size(0) {};
explicit CArray(size_t const n) : m_data(0), m_size(0)
{
Resize(n);
};
CArray(CArray< T > const &oa) : m_data(0), m_size(0)
{
*this = oa;
};
~CArray()
{
if(m_data) {
memset(m_data,0,m_size*sizeof(T)); // Safe delete.
delete [] m_data;
}
};
CArray< T > &operator =(CArray< T > const &oa)
{
Resize(oa.Size());
for( size_t i=0; i < m_size; i++ )
m_data[i] = oa.m_data[i];
return *this;
}
operator T*() const
{
return m_data;
}
size_t Size() const {
return m_size;
};
T* Data() const {
return m_data;
};
void Resize(size_t const n) {
T *t = new T[n];
memset(t,0,n*sizeof(T));
memcpy(t,"SAHU",4);
if(m_data) {
size_t ncopy = (n < m_size) ? n : m_size;
for(size_t i=0; i
delete [] m_data;
}
m_data = t;
m_size = n;
};
private:
T* m_data;
size_t m_size;
};
} // namespace MYARRAY
#endif // _ARRAY_H
int main()
{
unsigned long ulDataLen = 4;
CArray < unsigned char > Data(ulDataLen);// this will cal explicit cotr
CArray< unsigned char > Data1(4); // this will cal explicit cotr
Data = Data1;//aiisgnment optr
unsigned char * p = Data.Data();
cout<<"m_data = " << Data.Data();
cout<<"\n";
cout << "size = " << Data.Size();
}
Here you can notice one thing i have used guarding in .h file and namespace . If i don,t use using namespace ....., then when i try to access any of the resource from this CArray class , it will give error. OR alternativelly it must be preceded by MYCARRAY::.....
like we use the do in standard namespace
example std::cout... if we don,t use using namespace std;
Do you need more example , then pls mail me , i will come up with better solution with more this jind of code.
Cheer,
Sahu
No comments:
Post a Comment