@f1o

В чем мои ошибки в коде?

Написал решение части задания, но оно работает не верно. помогите пожалуйста найти ошибки и скажите как их исправить и в чем мой пробел.
Ошибки появляются в:
  • z.checkElem(2) возвращает не верное значение
  • z.setPrint(5); после ввода элемента выводит 9 элементов 6 из которых не известы включая тот что задавался ранее и выводился нормально
  • n.deletElemByIndex(1); удаляет но проблемма такая же как и выше не выводится элемент заданный в z.addItem(5)


Подскажите что у меня не так. мне кажется что все ошибки исходят из-за неправильного изменения элементов arr.

Простыня кода
template <class T> 
class SetOfNumb {
	private:
		int size;
		T *arr;
	public:
		SetOfNumb():size(0) {
			arr = new T[size];
		}
		
		SetOfNumb(int a[]) {
			size = sizeof(a)-1;
			arr = new T[size];

			for (int i = 0; i < size; i++) {
				arr[i] = a[i];
			}
		}

		SetOfNumb(int a[], int elem) {
			size = sizeof(a);
			arr = new T[size];

			for (int i = 0; i < size; i++) {
				arr[i] = a[i];
			}
			arr[size] = elem;
		}

		SetOfNumb(SetOfNumb &temp) {
			size = temp.size;
			arr = new T[size];

			for (int i = 0; i < size; i++) {
				arr[i] = temp.arr[i];
			}
		}

		~SetOfNumb() {
			delete[] arr;
		}

		void addItem(int elem) {
			SetOfNumb<int> temp(arr);
			size++;
			delete[] arr;
			arr = new T[size];
			for (int i = 0; i < size; i++) {
				arr[i] = temp.arr[i];
			}
			arr[size-1] = elem;
		}

		void deletElemByIndex(int index) {
			SetOfNumb<int> temp(arr);
			delete[] arr;
			size--;
			temp.print();
			std::cout << std::endl;
			arr = new T[size];
			temp.print();
			std::cout << std::endl;
			for (int i = 0, j = 0; i < sizeof(temp.arr); i++) {
				if (i != index) {
					arr[j] = temp.arr[i];
					j++;
				}
			}
		}

		void setPrint(int count) {
			int in = 0;
			for (int i = 0; i < count; i++) {
				std::cout << "enter count: " << std::endl;
				std::cin >> in;
				addItem(in);
			}
			
			print();
		}

		bool checkElem(int item) {
			for (int i = 0; i < size; i++) {
				if (arr[i] == item) { return true; }
				else { return false; }
			}
		}

		void print() {
			for (int i = 0; i<size; i++) {
				std::cout << arr[i];
			}
		}
};

int main() {
	SetOfNumb<int> n;
	int arr[3] = {1, 2, 3};
	SetOfNumb<int> z(arr);
	z.print();
	std::cout << std::endl;
	z.addItem(5);
	
	

	z.print();
	std::cout << std::endl;
	std::cout << z.checkElem(2) << std::endl;
	if (z.checkElem(2)) {
		std::cout << "y" << std::endl;
	}
	else {
		std::cout << "n" << std::endl;
	}
	n = z;
	z.setPrint(5);
	n.print();
	std::cout << std::endl;
	n.deletElemByIndex(1);
	n.print();
	std::cout << std::endl;

	system("pause");
	return 0;
};
  • Вопрос задан
  • 298 просмотров
Пригласить эксперта
Ответы на вопрос 1
Andrey2008
@Andrey2008
DevRel в PVS-Studio
Не знаю касательно корректности алгоритма, но PVS-Studio обнаруживает 4 ошибки, из-за которых уже и так всё работает не так как надо.
SetOfNumb(int a[]) {
size = sizeof(a)-1;
V511 The sizeof() operator returns size of the pointer, and not of the array, in 'sizeof (a)' expression. consoleapplication2017.cpp 37
Оператор sizeof вычислят здесь размер указателя, а не массива. В результате, переменная size всегда будет равна 3 в 32-битной программе или 7 в 64-битной программе.

Аналогично здесь:
size = sizeof(a);
V511 The sizeof() operator returns size of the pointer, and not of the array, in 'sizeof (a)' expression. consoleapplication2017.cpp 46

И здесь:
for (int i = 0, j = 0; i < sizeof(temp.arr); i++) {

V604 It is odd that the number of iterations in the loop equals to the size of the 'temp.arr' pointer. consoleapplication2017.cpp 88

Ещё происходит ошибка копирования:
n = z;
V1002 The 'SetOfNumb' class, containing pointers, constructor and destructor, is copied by the automatically generated operator=. consoleapplication2017.cpp 140
Класс SetOfNumb сложный, выделяет память. Но при этом отсутствует operator =. В результате просто копируются члены класса, что приведёт к двойному освобождению памяти.
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы