C ++创建动态对象数组?

时间:2014-10-22 23:34:48

标签: c++ arrays pointers dynamic

#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

的相同值创建每个对象

非常感谢任何输入

编辑:以下代码是我试图在上面解释的:

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
}

然而,当我收到错误时,这不会编译:

  

错误C4703:可能未初始化的本地指针变量&#39; pResistor&#39;使用

1 个答案:

答案 0 :(得分:0)

srand(GetTickCount());
Resistor * pResistor = NULL; 
vector<Resistor*> resList;
int numberOfResistors = 50; // Use your cin cout here
for (size_t i = 0; i < numberOfResistors; i++)
{
    pResistor = new Resistor;
    // Assuming some sort of pResistor->SetResistance( /* val */ )
    resList.push_back(pResistor);
}

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 " << resList[i]->getResistance() << " " << (char)234 << endl;  // Display value of resistor pointed to by pResistor
}

cout << "number of resistors : " << resList.size() << endl;

每个电阻都需要自己的参考,所有参考都必须添加到有序列表中。 std :: vector用于制作有序列表

相关问题