#include "resistor.h"
void main() {
srand(GetTickCount()); // Lewt's start by seeding the random number generator so that different runs of our program will always yield fifferent results
Resistor * pResistor; // Pointer to a resistor class
int numberOfResistors = 0; // Variable will hold the user choice of the number of resistors to be created
cout << "How many resistors do you want to create?" << endl; // prompt user
cin >> numberOfResistors; // Allow the user to enter the number of resistors to be created
pResistor = new Resistor[numberOfResistors]; // Create an array of objects of class resistor and assign its address to our pointer
// You will notice that there is a logic error here. All the resistors will have the same value. This
// is because they were all created at once. To address this issue we need to create each object
// of the class resistor separately. This means using a loop. This will be up to you to do
// It should be a very easy fix
for (int i = 0; i< numberOfResistors; i++) { // This loop will be used to display the resistor values
cout << "Resistor # " << i + 1 << " has a value of " << pResistor->getResistance() << " " << (char)234 << endl; // Display value of resistor pointed to by pResistor
}
cout << "So far, we have created " << pResistor->getNumerOfResistors() << " resistor(s)" << endl; // Display total number of resistors
delete[] pResistor; // Delete the array that was created and release the memory that was allocated.
} // end of main
Я занимаюсь этим кодом для присвоения класса. Как вы, наверное, видите в комментариях, есть логическая ошибка, которую мой преподаватель вложил туда, и мне нужно ее исправить. Я попытался поместить строку pResistor = new Resistor[numberOfResistors];
внутри цикла for, который запускает количество раз, вызванное пользовательским вводом (вместо создания массива). Проблема еще, что каждый объект по-прежнему создается с тем же значением для ResistorObject.resistance
C++ создает динамический массив объектов?
Любой вклад будет высоко ценится
EDIT: Следующий код, что я пытался объяснить выше:
for (int i = 0; i < numberOfResistors; i++) {
pResistor = new Resistor[i]; // Create an array of objects of class resistor and assign its address to our pointer
}
Это, однако, не будет компилироваться, как я получаю ошибку:
error C4703: potentially uninitialized local pointer variable 'pResistor' used
Как вы устанавливаете сопротивление? Является ли он указан в пользовательском (не умолчанию) конструкторе? Должны ли вы использовать ГСЧ для этого? – user3353819
Вам не нужно комментировать каждую строку кода - мы знаем C++. Более комментирование делает ваш код более трудным для чтения. – zch
Векторы - это очевидный подход, например, показания пользователя user3670482s. Вектор содержит много индивидуальных указателей на разные резисторы, которые каждый получает выделенным и, таким образом, может иметь свое сопротивление, установленное по-разному, но опять же, как вы устанавливаете сопротивление? Кроме того, вы должны делать это без векторов? – user3353819