下面是 date.h ,日期。cpp 和 main.cpp 我没有收到任何编译错误。但是exe的运行停止,当删除日期类的checkday功能时不会发生这种情况。功能有什么问题?我正在使用开发 C++
#ifndef DATE_H
#define DATE_H
class Date{
private:
int day, month, year;
public:
Date(int = 1, int = 1, int = 1990);
~Date();
void setDay(int);
int checkDay(int); //return int i.e. default day 1 or correct date inputted :)
void setMonth(int);
void setYear(int);
int getDay() const;
int getMonth() const;
int getYear() const;
void printDate() const;
};
#endif
#include <iostream>
#include <cmath>
using namespace std;
#include "date.h"
Date::Date(int d, int m, int y){
//setDay(d); calling setDay() here caused crash
setMonth(m);
setYear(y);
setDay(d);
}
Date::~Date(){
cout<<"Date destructor called...\n";
}
void Date::setDay(int d){
day = checkDay ( d ) ;
}
int Date::checkDay(int dd){ /*COMMENTING THIS FUNCTION REMOVES RUN TIME ERROR */
static int daysInmonth[13] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
if ( dd > 0 && dd <= daysInmonth[month] )
return dd;
if( ( year%400==0||( year%100!=0 && year%4==0))&& month==2 && dd==29)
return dd;
return 1;
}
void Date::setMonth(int m){
month = ((m > 0 && m <=12) ? m : 1 );
}
void Date::setYear(int y){
if (((int)log10((double)y) + 1)!=4) //ild1 != 4
year = 1990;
else year = y;
}
int Date::getDay() const{
return day;
}
int Date::getMonth() const{
return month;
}
int Date::getYear() const{
return year;
}
void Date::printDate() const{
cout<<"Date: "<<getDay()<<"/"<<getMonth()<<"/"<<getYear()<<endl;
}
#include <cstdlib>
#include <iostream>
#include "date.h"
using namespace std;
int main()
{
Date date1( 2, 3, 2004),date2,date3( 2, 1, -1980),
date4(0, 12, 2990),date5(29, 2, 2001), date6(12,12, 98686);
cout<<"User inputted valid date: "; date1.printDate();
cout<<"\nDefault valid date: "; date2.printDate();
cout<<"\nAttempt to input invalid date: 2/1/-1980 "; date3.printDate();
cout<<"\nAttempt to input invalid date: 0/12/2990 "; date4.printDate();
cout<<"\nAttempt to input invalid date: 29/2/2001 ( non leap year) "; date5.printDate();
cout<<"\nAttempt to input invalid date: 12/12/98686 "; date6.printDate();
cout<<endl;
system("PAUSE");
return EXIT_SUCCESS;
}