把compare的参数设置成const就无法调用公有函数?
int compare(const Date& d){
if(d.toInt()>toInt()){
return 1;
}
else if(d.toInt()<toInt()){
return -1;
}
return 0;
}
报错如下
[Error] passing 'const Date' as 'this' argument of 'int Date::toInt()' discards qualifiers [-fpermissive]
不管调哪个函数都不让过编译
#include<iostream>
#include<string>
using namespace std;
class Date{
private :
int year,month,day;
public :
Date(int y=1900,int m=1,int d=1):year(y),month(m),day(d){}
Date(const string&s){
int a=0;
for(int i=0;i<4;++i){
a=a*10+s[i]-'0';
}
year=a;
a=0;
for(int i=5;i<7;++i){
a=a*10+s[i]-'0';
}
month=a;
a=0;
for(int i=8;i<10;++i){
a=a*10+s[i]-'0';
}
day=a;
}
void set(int y,int m,int d){
year=y;
month=m;
day=d;
}
bool isValid(){
int d[12]={31,28,31,30,31,30,31,31,30,31,30,31};
int d2[12]={31,29,31,30,31,30,31,31,30,31,30,31};
if(isLeapYear()&&month<=12&&month>=1&&day<=d2[month-1]&&day>0){
return true;
}
if(!isLeapYear()&&month<=12&&month>=1&&day<=d[month-1]&&day>0){
return true;
}
return false;
}
bool isLeapYear(){
if(year%100!=0&&year%4==0||year%400==0){
return true;
}
return false;
}
int toInt(){
int x;
x=year*10000;
x+=month*100;
x+=day;
return x;
}
Date lastDay(){
Date x;
int d[12]={31,28,31,30,31,30,31,31,30,31,30,31};
int d2[12]={31,29,31,30,31,30,31,31,30,31,30,31};
if(month==1&&day==1){
x.set(year-1,12,31);
}
else if(isLeapYear()&&day==1){
x.set(year,month-1,d2[month-2]);
}
else if(!isLeapYear()&&day==1){
x.set(year,month-1,d[month-2]);
}
else x.set(year,month,day-1);
return x;
}
Date nextDay(){
Date x;
int d[12]={31,28,31,30,31,30,31,31,30,31,30,31};
int d2[12]={31,29,31,30,31,30,31,31,30,31,30,31};
if(month==12&&day==31){
x.set(year+1,1,1);
}
else if(isLeapYear()&&day==d2[month-1]){
x.set(year,month+1,1);
}
else if(!isLeapYear()&&day==d[month-1]){
x.set(year,month+1,1);
}
else x.set(year,month,day+1);
return x;
}
void print(){
cout<<year<<'-'<<month<<'-'<<day<<endl;
}
int getYear(){
return year;
}
int getMonth(){
return month;
}
int getDay(){
return day;
}
void setYear(int y){
year=y;
}
void setMonth(int m){
month=m;
}
void setDay(int d){
day=d;
}
int compare(const Date& d){
if(d.toInt()>toInt()){
return 1;
}
else if(d.toInt()<toInt()){
return -1;
}
return 0;
}
};
int main(){
Date today(2023,3,15);
Date yesterday("2023/3/14");
Date theday;
theday.set(2222,2,29);
cout<<"2222年是闰年吗?"<<endl;
cout<<theday.isLeapYear()<<endl;
cout<<"theday是合法的日期吗?"<<endl;
cout<<theday.isValid()<<endl;
cout<<"数字化"<<endl;
cout<<theday.toInt()<<endl;
cout<<"昨天的前一天是"<<endl;
yesterday.lastDay().print();
cout<<"今天的后一天是"<<endl;
today.nextDay().print();
cout<<"今天是几几年?"<<endl;
cout<<today.getYear()<<endl;
cout<<"今天是几月?"<<endl;
cout<<today.getMonth()<<endl;
cout<<"今天是几号?"<<endl;
cout<<today.getDay()<<endl;
cout<<"随便输入一个日期,看看是在今天前面还是后面"<<endl;
int y,m,d;
cin>>y>>m>>d;
Date aday;
aday.setYear(y);
aday.setMonth(m);
aday.setDay(d);
if(today.compare(aday)>0){
cout<<"在今天后面"<<endl;
}
else if(today.compare(aday)<0){
cout<<"在今天前面"<<endl;
}
else cout<<"是同一个日期啊"<<endl;
}