Why does the compiler say "undeclared identifier" for a variable I declared in the "if" statement just above?

StackOverflow https://stackoverflow.com/questions/22771998

Pregunta

Why is this throwing an error, undeclared identifier?

void IDcard::Prepare(CoatingDecorator *coating)
{
    if (select == 1) { IDcard *currentID = new Passport(); }
    else if (select == 2) { IDcard *currentID = new DriversLicence();   }

    AddPhoto();
    coating->Prepare(currentID);
    std::cout << "Total Cost: " << coating->totalCost; 
    DispenseID();
}

(specifically currentID parameter when calling coating->Prepare(currentID)).

As far as I can tell currentID is declared in the if statements.

Running this on MS VS2012, error code is C2065.

¿Fue útil?

Solución

currentID only exist in the if and the else, outside that its not declared, you can declare it before the IF and initialize inside the IF and Else.

Also as commented if select its not 1 or 2 it would not be initialized and can cause problems so make sure to initialize it.

void IDcard::Prepare(CoatingDecorator *coating)
{
IDcard *currentID;

if (select == 1) { currentID = new Passport(); }
else if (select == 2) { currentID = new DriversLicence();   }

AddPhoto();
coating->Prepare(currentID);
std::cout << "Total Cost: " << coating->totalCost; 
DispenseID();
}

Otros consejos

You can declare the currentID outside the if block to fix the error.

void IDcard::Prepare(CoatingDecorator *coating)
{
  IDcard *currentID = NULL;
  if (select == 1) { currentID = new Passport(); }
  else if (select == 2) { currentID = new DriversLicence();   }

  AddPhoto();
  coating->Prepare(currentID);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top