简体   繁体   English

重定义错误 C++

[英]Redefinition Error C++

I am having trouble with the portion where I need to print the day.我在需要打印当天的部分时遇到问题。 I tried making a second variable but it is not working.我尝试制作第二个变量,但它不起作用。 Basically I take a user input for their birthday.基本上我会为他们的生日输入用户输入。 Then I'm trying to call this function that determines the day of birth (it determines a number that represents a day).然后我试图调用这个确定出生日期的函数(它确定一个代表一天的数字)。 Then I am trying to send this number to the function that takes the number and prints the birthday day in words.然后我试图将这个数字发送到接收这个数字并用文字打印生日的函数。 I am now getting the error that 'int day2' redefinition.我现在收到'int day2'重新定义的错误。

Here is my code:这是我的代码:

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

Remove the int from the second assignment, you can't define a variable twice in the same block.从第二次赋值中删除int ,您不能在同一块中两次定义变量。

To fix your code, replace:要修复您的代码,请替换:

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

With:和:

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

You have put two times "int day2", which indeed is a redefinition.您输入了两次“int day2”,这确实是重新定义。 You have to define "day2" only once:您只需定义“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;

The cause of the problem is问题的原因是

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

The second is a redefinition of day2 .第二个是重新定义day2

Remove the int keyword from that line, and it will become a simple assignment.从该行中删除int关键字,它将成为一个简单的赋值。

you can't declare two variables in the same scope so day2 is declared twice in your if block.您不能在同一范围内声明两个变量,因此在 if 块中将 day2 声明了两次。 you can directly write:你可以直接写:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM