【问题标题】:Why does this tell me that "gender" is an undeclared identifier on line为什么这告诉我“性别”是在线未声明的标识符
【发布时间】:2016-10-20 19:56:32
【问题描述】:
int main()
{
    introduction();
    int x;
    cin >> x;
    if (x == 1)
        cout << endl << "1. Only state true information." << endl << "2. Do not copy this servey and distribute it AT ALL." << endl << "3. Do not falsely advertise this survey anywhere." << endl << endl;
    cout << "(Press 1 to start survey)" << endl;
    int y;
    cin >> y;
    if (y == 1)
        int gender = askGender();
    int job = askJobOrNot();
    int sport = askFavSport();
    int music = askFavMusicGenre();
    int birth = askBirthPlace();
    int colour = askFavColour();
    cout << endl << "Thank you, you have successfully completed the survey! (:  " << endl;
    cout << "(Press 1 to show results, and press 2 to quit)" << endl;
    int s;
    cin >> s;
    if (s == 1)
        printResults(gender, job, sport, music, birth, colour);
    if (s == 2)
        quitProgram();
    return 0;
}

当我编译这段代码时,它在第 23 行给了我一个错误,告诉我变量“gender”(我作为参数放在函数“printResults”中)是一个未声明的标识符,即使我明确声明了它之前的 11 行(第 12 行)。为什么会这样?

【问题讨论】:

  • 您在if 语句的范围内声明了gender。在您想使用它的时候它已经消失了。
  • 该变量仅在前面的if() 语句的范围内声明。
  • 也许这会澄清为什么会这样:en.cppreference.com/w/cpp/language/scope
  • 你需要在'if'语句之外(在if(y==1)之前)声明'gender'变量,这样它就可以在整个程序中被访问,现在它被声明了'if' 条件范围,这就是为什么当您将性别作为参数传递给 printResult 时,它无法识别性别。所以错误是。

标签: c++ variables compiler-errors xcode5 undeclared-identifier


【解决方案1】:

改变这个:

if (y == 1)
    int gender = askGender();

到这里:

int gender;
if (y == 1)
    gender = askGender();

或者甚至更好:

int gender = 0; // default: 0
if (y == 1)
    gender = askGender();

【讨论】:

    猜你喜欢
    • 2010-11-15
    • 2022-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-29
    相关资源
    最近更新 更多