[問題] C++寫class Date
開發平台(Platform): (Ex: VC++, GCC, Linux, ...)
code::block gcc
額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
問題(Question):
在寫difference函數時,dayd += d.dayInYear() + d.day;
這一行一直出現錯誤訊息,但又不知道如何改?
error: passing `const Date' as 'this' argument of `int Date::dayInYear()'
discards qualifiers
程式碼:
#include "Date.h"
#include<stdio.h>
using namespace std;
Date::Date(int month, int day, int year)
{
if(isValidDate(month,day,year)){
this->day = day;
this->month = month;
this->year = year;
}
else{
cout<<"Your date is invalid";
}
}
Date::Date(const string& s)
{
int d,m,yr,ret=0;
if((ret = sscanf(s.c_str(),"%d/%d/%d",&m,&d,&yr))==3){
this->year = yr;
this->month = m;
this->day = d;
}
else{
cout<<"error";
}
}
bool Date::isLeapYear(int year) { //Checked
if((year%4==0&&year%100!=0)||(year%400==0))
return true;
else
return false;
}
int Date::daysInMonth(int month, int year) //Checked
{
int paraday[] = {31,28,31,30,31,30,31,31,30,31,30,31};
if(isLeapYear(year))
paraday[1] = 29;
return paraday[month-1];
}
bool Date::isValidDate(int month, int day, int year) { //Checked
if(year<0)
return false;
else if(month>12&&month<1)
return false;
else if(daysInMonth(month,year) < day && day<1)
return false;
else
return true;
}
string Date::toString() {
char buf[11];
sprintf(buf,"%d/%d/%d",this->month,this->day,this->year);
string *s = new string(buf);
return *s; // replace this line with your solution
}
bool Date::isBefore(const Date& d)
{
if(difference(d)>0)
return true;
else
return false;
}
bool Date::isAfter(const Date& d) {
if(isBefore(d) || isEqual(d))
return false;
else
return true;
}
bool Date::isEqual(const Date& d)
{
if(difference(d)==0)
return true;
else
return false;
}
int Date::dayInYear() { //Checked,but object???
if(isLeapYear(this->year))
return 366;
else
return 365;
}
int Date::difference(const Date& d)
{
int paradaythis[] = {31,28,31,30,31,30,31,31,30,31,30,31};
int paradaydayd[] = {31,28,31,30,31,30,31,31,30,31,30,31};
int diff,dayd=0,daythis=0;
if(isLeapYear(this->year)){
paradaythis[1] = 29;
}
if(isLeapYear(d.year)){
paradaydayd[1] = 29;
}
for(int i=0;i < month - 1;i++){
daythis += paradaythis[i];
}
daythis += dayInYear() + day;
for(int i=0;i<d.month-1;i++){
dayd += paradaydayd[i];
}
dayd += d.dayInYear() + d.day;
diff = daythis - dayd;
return diff;
}
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.112.217.37
※ 編輯: target8917 來自: 140.112.217.37 (11/02 00:11)
推
11/02 00:19, , 1F
11/02 00:19, 1F
→
11/02 00:20, , 2F
11/02 00:20, 2F
→
11/05 20:40, , 3F
11/05 20:40, 3F