【问题标题】:Why does the compiler say "undeclared identifier" for a variable I declared in the "if" statement just above?为什么编译器对我在上面的“if”语句中声明的变量说“未声明的标识符”?
【发布时间】:2014-03-31 20:55:31
【问题描述】:

为什么会抛出错误,未声明的标识符?

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();
}

(特别是在调用coating-&gt;Prepare(currentID)时的currentID参数)。

据我所知,currentID 是在 if 语句中声明的。

在 MS VS2012 上运行,错误代码为 C2065。

【问题讨论】:

  • currentID 只存在于它被声明的范围内。
  • 在 if 语句中?
  • 除了@juanchopanza 说的,select 是在哪里声明的?我假设它是会员/全球?
  • @nonsensickle,它在类声明中声明

标签: c++ parameters undeclared-identifier


【解决方案1】:

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();
}

【讨论】:

  • 您能否解释一下如果代码保持原样,currentID 可能保持未初始化状态?之后它将是 +1。
  • 太棒了,谢谢@LuisTellez,我犯了一个愚蠢的错误,但你可能为我节省了几个小时
  • @LuisTellez 感谢更新的答案,非常有用并解决了我的问题
【解决方案2】:

您可以在 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);

【讨论】:

  • @LuisTellez 更快,但你更正确。 +1。
  • 为什么 = NULL,不会是 = new IDcard(); ??
  • @user3001499 这意味着IDcard() 是我们不知道的可构造。同样,将指针初始化为 null 是标准做法,尽管通常您不会使用 NULL 而是使用 0(即 IDcard *currentID = 0 是更好的选择)。
猜你喜欢
  • 2022-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多