Hello to all i have below code
in PointArray.h
#ifndef POINTARRAY_H_INCLUDED
#define POINTARRAY_H_INCLUDED
template <typename T>
class PointArray
{
private:
int nSize;
T *array[];
public:
PointArray();
PointArray(const T *points[],const int size);
PointArray(const PointArray &pv);
~PointArray();
int * get(const int position);//is same to array[position]
const int * get(const int position) const;//is same to array[position]
const int getSize() const;//get size of array
};
#endif // POINTARRAY_H_INCLUDED
in PointArray.cpp
#include "PointArray.h"
#include<iostream>
#include <assert.h>
using namespace std;
template<class T>
PointArray<T>::PointArray(const T *points[],const int size)
{
nSize=size;
for (int i=0;i<size;i++)
{
array[i]=new T;
*array[i]=*points[i];
}
}
template<class T>
PointArray<T>::PointArray()
{
nSize=0;
}
template<class T>
PointArray<T>::PointArray(const PointArray &pv)
{
nSize=pv.getSize();
for (int i=0;i<nSize;i++)
{
array[i]=new T;
*array[i]=*(pv.get(i));
}
}
template<class T>
const int PointArray<T>::getSize() const
{
return nSize;
}
template<class T>
PointArray<T>::~PointArray()
{
delete[] array;
nSize=0;
}
template<class T>
int * PointArray<T>::get(const int position)
{
assert(position>-1 && position<nSize);
return array[position];
}
template<class T>
const int * PointArray<T>::get(const int position) const
{
return array[position];
}
in main.cpp
#include<iostream>
#include "PointArray.h"
#include "PointArray.cpp"
using namespace std;
int main()
{
int x=22;
int y=3;
const int * a[2]={&x,&y};
PointArray<int> p;
PointArray<int> p2(a,2);
PointArray<int> p3(p2);
cout << p.getSize() << endl;
cout << p2.getSize() << endl;
cout << p3.getSize() << endl;
return 0;
}
above code should print
0
2
2
but output is
9244616
9244600
2
and when i run it again 9244616
, 9244600
is changed.
what is problem?