c++重定义错误

Redefinition Error C++

本文关键字:错误 定义 c++      更新时间:2023-10-16

我在需要打印日期的部分遇到了麻烦。我试着做第二个变量,但它不工作。基本上,我会输入用户的生日。然后我尝试调用这个函数来确定出生日期(它确定一个代表一天的数字)。然后,我尝试将这个数字发送给函数,该函数接受该数字并以单词形式打印生日。我现在得到的错误是'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关键字,它将成为一个简单的赋值

你不能在同一个作用域中声明两个变量,所以day2在if块中声明了两次。你可以直接写:

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