簡體   English   中英

重定義錯誤 C++

[英]Redefinition Error C++

我在需要打印當天的部分時遇到問題。 我嘗試制作第二個變量,但它不起作用。 基本上我會為他們的生日輸入用戶輸入。 然后我試圖調用這個確定出生日期的函數(它確定一個代表一天的數字)。 然后我試圖將這個數字發送到接收這個數字並用文字打印生日的函數。 我現在收到'int day2'重新定義的錯誤。

這是我的代碼:

void determineDayOfBirth() {

    int day;
    int month;
    int year;
    char backslash;
    char backslash2;

    cout << "Enter your date of birth" << endl;
    cout << "format: month / day / year -->" << endl;
    cin >> month >> backslash >> day >> backslash2 >> year;

    if (isValidDate(month, day, year)) {
        int day2;
        cout << "You were born on a: ";
        int day2 = determineDay(month, day, year);
        printDayOfBirth(day2); 
        cout << endl;
        cout << "Have a great birthday!!!";
    }
    else {
        cout << "Invalid date";
    }
    return;
}

從第二次賦值中刪除int ,您不能在同一塊中兩次定義變量。

要修復您的代碼,請替換:

int day2;
cout << "You were born on a: ";
int day2 = determineDay(month, day, year);

和:

cout << "You were born on a: ";
int day2 = determineDay(month, day, year);

您輸入了兩次“int day2”,這確實是重新定義。 您只需定義“day2”一次:

if (isValidDate(month, day, year)) {
    int day2;
    cout << "You were born on a: ";
    day2 = determineDay(month, day, year); // REMOVE "int"
    printDayOfBirth(day2); 
    cout << endl;
    cout << "Have a great birthday!!!";
}
else {
    cout << "Invalid date";
}
return;

問題的原因是

    int day2;
    cout << "You were born on a: ";
    int day2 = determineDay(month, day, year);

第二個是重新定義day2

從該行中刪除int關鍵字,它將成為一個簡單的賦值。

您不能在同一范圍內聲明兩個變量,因此在 if 塊中將 day2 聲明了兩次。 你可以直接寫:

//if(){
     int day2 = determineDay(month, day, year);
//}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM