У меня также есть некоторые ошибки с конструктором копирования, которые я не могу понять, но главный вопрос на данный момент излагается в моих комментариях к тестовым программам. Почему вторая распечатка такого большого количества, а не три? Заранее благодарим за помощь.
template<class T>
class Array {
private:
T *cont;
unsigned int size;
public:
Array()=default;
T& elementAt(unsigned int i)
{
return cont[i];
}
Array( const Array &a )
{
cont = new int[ size ];
for ( int i = 0; i < size; i++ )
cont[ i ] = a.cont[ i ];
}
Array& operator = (const Array& a)
{
int i,min_size;
if(size < a.size)
min_size = size;
else
min_size = a.size;
for(i=0; i<min_size; i++)
cont[i] = a.cont[i];
return (*this);
}
void addElement(T element) {
T *new_cont = new T[size + 1], *old_cont = cont;
for (int i = 0; i < size; i++) {
new_cont[i] = old_cont[i];
}
new_cont[size] = element;
size++;
cont = new_cont;
delete old_cont;
}
unsigned int getSize() const
{
return size;
}
~Array()
{
delete [] cont;
}
};
И эта часть моей тестовой программы:
Array<int> numbers;
numbers.addElement (5);
numbers.addElement (11);
numbers.addElement (3);
cout << numbers.getSize()<<endl; // Here I get output: 3
cout<< numbers.elementAt(1)<<endl; // output: 11
MyArray<int> copy2;
copy2 = numbers;
cout << copy2.getSize()<<endl; // WHY is output: 2686697, in here? Why isn' t it 3.
cout<< copy2.elementAt(1)<<endl; // output: 11
Вы используете неправильный size
для выделения памяти в конструкторе копирования.
Array( const Array &a )
{
// Get the size from the copy first. Without it, size is an unitialized
// value, which will lead to undefined behavior.
size = a.size;
cont = new int[ size ];
for ( int i = 0; i < size; i++ )
cont[ i ] = a.cont[ i ];
}
Другая проблема, которую я вижу, - это реализация конструктора по умолчанию. Конструктор по умолчанию может использоваться двумя способами:
Array<int> numbers;
или
Array<int> numbers = Array<int>();
Первая приведет к неинициализированным данным, в то время как последняя приведет к правильно инициализированным данным с вашей реализацией. Подробнее см. Здесь.
Вы можете изменить конструктор по умолчанию:
Array() : size(0), cont(NULL) {}
чтобы ваш код работал одинаково в любом случае для создания объекта.
Третья проблема - operator=
функция. Он не выполняет истинное задание. Он хранит только минимальное количество элементов из двух объектов. Попробуй это:
Array& operator = (const Array& a)
{
// Make statements like 'a = a;' a noop.
if ( this != &a )
{
// If the size of the LHS is larger than or equal to the size
// of the RHS, the LHS has enough memory to store the data
// from the RHS.
if ( this->size >= a.size )
{
this->size = a.size;
for(int i=0; i<a.size; i++)
cont[i] = a.cont[i];
}
else
{
// The size of the LHS is smaller than the size of the RHS,
// It does not have enough memory to store the data from
// the RHS. Dellocate old memory. Allocate new memory.
// Then copy the data.
this->size = a.size;
delete [] cont;
cont = new int[this->size];
for(int i=0; i<a.size; i++)
cont[i] = a.cont[i];
}
}
return (*this);
}
В то время, когда вы вызываете свой конструктор копирования, член size
не инициализируется. Вы, вероятно,
size = a.size; // Initialize size member also, it not done automagically
cont = new int[ size ];
в вашем конструкторе копирования.
size = a.size;
на первой линии.
Вы должны получить размер от объекта a
Array( const Array &a )
{
cont = new int[ a.size ];
for ( int i = 0; i < a.size; i++ )
cont[ i ] = a.cont[ i ];
}
size = a.size;
на первой линии.
cont = new int[ size ];
должен бытьcont = new int[ a.size ];
в вашем конструкторе копирования.Array( const Array &a )
вы должны добавитьsize = a.size;
на первой линии.