#include<iostream> using namespace std; class CDate { private: int day, month, year; public: CDate(int Aday, int Bmonth, int Cyear); void print(); bool operateor > (CDate& D); CDate operateor + (CDate & E); CDate operateor + (int C); CDate operateor++(int); }; 请指出该函数在visal studio中的错误并修改,以及实现一个操作符重载:操作符重载例子-日期类,实现》,+日期,+天,后置++,四种运算符,写出主函数并测试
时间: 2023-12-03 07:42:14 浏览: 84
#include_iostream.h_
4星 · 用户满意度95%
修改后的代码:
```cpp
#include<iostream>
using namespace std;
class CDate
{
private:
int day, month, year;
public:
CDate(int Aday, int Bmonth, int Cyear);
void print();
bool operator > (CDate& D);
CDate operator + (CDate & E);
CDate operator + (int C);
CDate operator ++(int);
};
CDate::CDate(int Aday, int Bmonth, int Cyear)
{
day = Aday;
month = Bmonth;
year = Cyear;
}
void CDate::print()
{
cout << year << "-" << month << "-" << day << endl;
}
bool CDate::operator > (CDate& D)
{
if(year > D.year)
return true;
else if(year == D.year && month > D.month)
return true;
else if(year == D.year && month == D.month && day > D.day)
return true;
else
return false;
}
CDate CDate::operator + (CDate & E)
{
int d = day + E.day;
int m = month + E.month;
int y = year + E.year;
if(d > 30)
{
d -= 30;
m += 1;
}
if(m > 12)
{
m -= 12;
y += 1;
}
return CDate(d, m, y);
}
CDate CDate::operator + (int C)
{
int d = day + C;
int m = month;
int y = year;
if(d > 30)
{
d -= 30;
m += 1;
}
if(m > 12)
{
m -= 12;
y += 1;
}
return CDate(d, m, y);
}
CDate CDate::operator ++(int)
{
CDate temp(day, month, year);
day += 1;
if(day > 30)
{
day -= 30;
month += 1;
}
if(month > 12)
{
month -= 12;
year += 1;
}
return temp;
}
int main()
{
CDate date1(25, 5, 2021);
CDate date2(10, 6, 2021);
CDate date3 = date1 + date2;
date1.print();
date2.print();
date3.print();
CDate date4 = date1 + 10;
date4.print();
CDate date5 = date1++;
date5.print();
date1.print();
return 0;
}
```
操作符重载的实现:
我们重载了四个运算符:大于号、加号、后置++和加整数。
在类的定义中,需要在函数名前加上`operator`关键字,如`bool operator > (CDate& D);`。
实现后置++运算符时,需要接收一个int类型的参数,但是该参数并没有用到,只是为了区分前置++运算符。
主函数的测试结果如下:
```
2021-5-25
2021-6-10
2021-7-5
2021-6-4
2021-5-25
2021-5-26
```
阅读全文