下面是 date.h ,日期。 cpp 和 main.cpp 我没有收到任何编译错误。但是 exe 的运行停止了,当日期类的检查日函数被删除时,这不会发生。该功能有什么问题?我正在使用开发 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;
}
最佳答案
在 checkDay() 中,您根据月份和年份对日期进行检查,但在 Date 构造函数中,当月份和年份尚未分配时,您首先从日期开始。
改变这个:
Date::Date(int d, int m, int y){
setDay(d);
setMonth(m);
setYear(y);
}
为此:
Date::Date(int d, int m, int y){
setMonth(m);
setYear(y);
setDay(d);
}
关于C++ Time 类在 checkDay 函数中没有编译错误、执行停止和应用程序崩溃错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13083072/