为什么会抛出错误,未声明的标识符?
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();
}
(调用currentID
时具体为coating->Prepare(currentID)
}。
据我所知,currentID是在if语句中声明的。
在MS VS2012上运行此命令,错误代码为C2065。
答案 0 :(得分:3)
currentID仅存在于if和else之外,在其未声明之外,您可以在IF之前声明它并在IF和Else内部初始化。
同样如果注释如果选择它不是1或2它将不会被初始化并且可能导致问题,所以一定要初始化它。
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();
}
答案 1 :(得分:0)
您可以在if块之外声明currentID来修复错误。
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);