把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
#include
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=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()"2023/3/14");
Date theday;
theday.set(2222,2,29);
cout<<"2222年是闰年吗?"<"theday是合法的日期吗?"<"数字化"<"昨天的前一天是"<print();
cout<<"今天的后一天是"<print();
cout<<"今天是几几年?"<"今天是几月?"<"今天是几号?"<"随便输入一个日期,看看是在今天前面还是后面"<>y>>m>>d;
Date aday;
aday.setYear(y);
aday.setMonth(m);
aday.setDay(d);
if(today.compare(aday)>0){
cout<<"在今天后面"<else if(today.compare(aday)<0){
cout<<"在今天前面"<else cout<<"是同一个日期啊"<
参考GPT和自己的思路:
这个问题是因为您在compare函数中使用了toInt函数,但是toInt函数不是const函数,因此无法在const函数中调用。解决方法是将toInt函数也声明为const函数,即在函数声明和定义中都加上const关键字,如下所示:
int toInt() const {
int x;
x=year*10000;
x+=month*100;
x+=day;
return x;
}
这样就可以在compare函数中调用toInt函数了。
两种方法
1.去掉const
2.在toint方法后面加const
如果你不能删除,也不能增加,那么你可以
int compare(const Date& d){
Date& temp=const_cast<Date&>d;
//再对temp做操作
return 0;
}
由于实验已经规定不能删除const,也不能增加const,所以无奈至此