构造函数
1,完成对象的初始化。
2,默认构造函数:1,无参,全缺省,自己不写编译器默认生成的,只能存在一个。
3,编译器生成的对内置类型不处理,只会去操作自定义类型,自定义类型调用自己的构造函数
Date::Date(int year , int month , int day )
{
if (year >= 1 &&
month >= 1 && month <= 12 &&
day >= 1)
{
_year = year;
_month = month;
_day = day;
}
else
{
cout << " 日期非法 " << endl;
}
}
拷贝构造函数
这里都是内置类型,其实也没必要写。 因为编译器默认生成的拷贝构造函数会完成浅拷贝/值拷贝
但是这里如果传值调用,就会引发无穷递归调用
Date::Date(const Date& d)
{
_year = d._year;
_month = d._month;
_day = d._day;
}
赋值重载
这里其实也没有必要写,编译器默认生成的赋值重载就可以完成,也是完成值拷贝/浅拷贝
//d1 = d2 -----> d1.operator=(&d1,d);
Date& Date::operator=(const Date& d)
{
if (this != &d)
{
_year = d._year;
_month = d._month;
_day = d._day;
}
return *this;
}
比较运算符的重载
我们只需要写一对,就可以完成复用了,
然后的话,这里可以直接放在类里面定义,默认成inline函数,因为他们比较短小
// >运算符重载 d1 > d2 ---->d1.operator>(&d1,d2)
bool operator>(const Date& d)
{
if (_year > d._year ||
(_year == d._year && _month > d._month) ||
(_year == d._year && _month > d._month && _day > d._day))
{
return true;
}
else
{
return false;
}
}
// // ==运算符重载 d1 == d2 ----->d1.operator(&d1 ,d2)
bool operator==(const Date& d)
{
if (_year == d._year &&
_month == d._month &&
_day == d._day)
{
return true;
}
else
{
return false;
}
}
// // >=运算符重载
bool operator >= (const Date& d)
{
return *this > d || *this == d;
}
// // <运算符重载
bool operator < (const Date& d)
{
return !(*this >= d);
}
// // <=运算符重载
bool operator <= (const Date& d)
{
return !(*this > d);
}
// // !=运算符重载
bool operator != (const Date& d)
{
return !(*this == d);
}
日期加减天数各种操作
// 日期+=天数 d1 += d2, 返回的是d2,出了函数作用域,仍旧存在,可以用引用返回
Date& Date::operator+=(int day)
{
_day += day;
while (_day > GetMonthDay(_year, _month))
{
_day -= GetMonthDay(_year, _month);
if (_month == 12)
{
_month = 0;
_year++;
}
_month++;
}
return *this;
}
// 日期+天数 d1 + 100 ,返回的是一个临时变量,出了函数作用域不存在
Date Date::operator+(int day)
{
//这里就可以复用+=了
Date ret(*this); //利用拷贝构造函数来初始化创建一个临时Date类
ret += day;
return ret;
}
复用+= ,和复用+,哪个效率高一些呢?,

/// 日期-天数
Date Date::operator-(int day)
{
Date ret(*this);
ret -= day;
return ret;
}
// // 日期-=天数
Date& Date::operator-=(int day)
{
_day -= day;
while (_day <= 0)
{
if (_month == 1)
{
_year--;
_month = 13;
}
_month--;
_day += GetMonthDay(_year,_month);
}
return *this;
}
前置和后置
// 前置++,++d1,d1加完1后再返回
Date& Date::operator++()
{
*this += 1;
return *this;
}
//// 后置++,d1++,先返回后++,返回的是临时变量,
// 并且我们规定,默认形参是int,不用传参
Date Date::operator++(int)
{
Date ret(*this);
*this += 1;
return ret;
}
//// 后置--
Date Date::operator--(int)
{
Date ret(*this);
*this -= 1;
return ret;
}
//// 前置--
Date& Date::operator--()
{
*this -= 1;
return *this;
}
日期减日期
// d1 - d2
int Date::operator-(const Date& d)
{
int flag = 1;
Date bigday(*this);
Date litterday(d);
if (*this < d)
{
litterday = *this;
bigday = d;
flag = -1;
}
int count = 0;
while (bigday != litterday)
{
count++;
litterday++;
}
return flag * count;
}
权限问题常常出错的地方
我们说,当在赋值或者传参的时候,权限只能缩小或者不变,一定不能变大


4720

被折叠的 条评论
为什么被折叠?



