- #1
JesseC
- 251
- 2
I'm trying to write a simple program to calculate the impedance of an AC circuit consisting of an arbitrary number of resistors, capacitors and inductors combined in series or parallel. First I ask the user to create the components they wish to use in the circuit, and this is where I hit the problem:
I know why this code fails, because the resistor object goes out of scope when the switch statement ends so the component library doesn't contain anything...
what I'm not sure about is how to get around this in a simple way?? I would hit the same problem with IF statements...
Code:
cout<< endl
<< "Please create the components you wish to use." << endl
<< "Enter R for a resistor, C for a capacitor, I for" << endl
<< "an inductor or enter 'S' to stop creating components." << endl;
char componentType;
cin >> componentType;
// vector of base class pointers to store the components
vector <component*> componentLibrary;
switch(componentType)
{
case 'r':
case 'R':
{
cout << "What is the resistance of the resistor in ohms?" << endl;
double tempResistance;
cin >> tempResistance;
// create resistor according to user input
resistor R(tempResistance);
// place resistor in component library
componentLibrary.push_back(&R);
break;
}
case 'c':
case 'C':
{
cout << "What is the capacitance in farads?" << endl;
...
... etc
}
cout << "Test Output:" << endl;
cout << componentLibrary[0]->getImpedance() << endl; // code fails here.
I know why this code fails, because the resistor object goes out of scope when the switch statement ends so the component library doesn't contain anything...
what I'm not sure about is how to get around this in a simple way?? I would hit the same problem with IF statements...