调试错误,abort()已在c ++中调用

时间:2013-11-28 22:51:29

标签: c++

我正在尝试对日期的初始值设定值执行错误检查,以便超出可接受范围的一天或一个月将停止程序进行重新布线,但即使在可接受的范围内,我也会收到调试错误。我不知道错误来自哪里,所以我发布了代码。

// ConsoleApplication56.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include<iostream>
#include<stdexcept>
#include<array>

using namespace std;

class Date
{
public:
    explicit Date(int mo, int da, int ye)
    {
        setDate( mo, da, ye);
    }
    void setDate(int &m, int &d, int &y)
    {

            setMonth(m);
            setDay(d);
            setYear(y);

    }
    void setMonth(int &m)
    {
        if (month>0 && month <13)
        {
        month = m;
        }else
            throw invalid_argument("month must be 1-12");
    }
    unsigned int getMonth()const
    {
        return month;
    }
    void setDay(int &d)
    {
        if(day>0 && day<32)
        {
        day = d;
        }else
            throw invalid_argument("day must be 0-31");
    }
    unsigned int getDay()const
    {
        return day;
    }
    void setYear(int &y)
    {
        year = y;

    }
    unsigned int getYear()const
    {
        return year;
    }
    void print()
    {
        cout<< month <<'/' << day << '/' << year;
    }
    void nextDay()
    {
        int numberOfDaysToAdd = 1;
    array <int,12> daysInAMonth = {31,28,31,30,31,30,31,31,30,31,30,31};

    cout << "the date before is: " << month << "/" << day << "/" << year << endl;

    day += numberOfDaysToAdd;

    while (day > daysInAMonth [month - 1 ] )
    {
        day-= daysInAMonth [month - 1 ];
        month++;

        if (month > 12){
          month = 1;
          year++;
        }

    }

    cout << "the day after is: " <<  month << "/" << day << "/" << year << endl;

    }

private:
    unsigned int month;
    unsigned int day;
    unsigned int year;
};


int main()
{
    char response = 'y';
    Date date(12, 3, 2013 );

    cout<<"The date is :";
    date.print();
    cout<<endl;
    cout<<endl;

    cout<<"do you wish to check the next date(y/n)? :";
    cin >> response;
    cout<<endl;

    while(response == 'y')
    {
    date.nextDay();
    cout<<endl;
    cout<<"do you wish to check the next date(y/n)? : ";
    cin >> response;
    cout<<endl;
    }
    return 0;

}

1 个答案:

答案 0 :(得分:2)

您应该检查md值,而不是monthday成员变量。

void setMonth(int &m)
{
  if (month>0 && month <13)

应该是

void setMonth(int &m)
{
  if (m>0 && m <13)