【问题标题】:Redefinition Error C++重定义错误 C++
【发布时间】:2017-02-17 00:28:17
【问题描述】:

我在需要打印当天的部分时遇到问题。我尝试制作第二个变量,但它不起作用。基本上我会为他们的生日接受用户输入。然后我试图调用这个确定出生日期的函数(它确定代表一天的数字)。然后我试图将此号码发送到获取号码并用文字打印生日的函数。我现在收到'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;
}

【问题讨论】:

  • 编译器应该怎么告诉你你已经重新定义了day2? .请再次检查您的代码,您将看到int day2 的两个声明。您只需在分配时使用名称。不需要第二个类型声明int

标签: c++ function pass-by-value redefinition


【解决方案1】:

从第二个赋值中删除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);

【讨论】:

    【解决方案2】:

    你已经放了两次“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;
    

    【讨论】:

      【解决方案3】:

      问题的原因是

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

      第二个是day2的重新定义。

      从该行中删除 int 关键字,它将变成一个简单的赋值。

      【讨论】:

        【解决方案4】:

        您不能在同一范围内声明两个变量,因此 day2 在您的 if 块中声明了两次。 你可以直接写:

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

        【讨论】:

          猜你喜欢
          • 2011-06-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-03-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多