64,282
社区成员
发帖
与我相关
我的任务
分享
myDate myDate::nextDay()
{
static int m[ 13 ] = { 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
int tempMonth = getMonth();
myDate tempMd = *this;
tempMd.day += 1;
if( tempMd.day > m[ tempMonth ] )
{
tempMd.day = 1;
tempMd.month += 1;
if( tempMd.month > 12 )
{
tempMd.year += 1;
tempMd.month = 1;
}
}
int y = getYear();
if(( y %400 == 0 )||( y % 100 != 0 && y % 4 == 0 ))
{
if( tempMonth == 2 && tempMd.day == 29 )
{
tempMd.day = 1;
tempMd.month = 3;
}
}
return tempMd;
}
myDate& myDate::nextDay1()
{
static int m[ 13 ] = { 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
int tempMonth = getMonth();
this->day += 1;
if( this->day > m[ tempMonth ] )
{
this->day = 1;
this->month += 1;
if( this->month > 12 )
{
this->year += 1;
this->month = 1;
}
}
int y = getYear();
if(( y % 400 == 0 )||( y % 100 != 0 && y % 4 == 0 ))
{
if( tempMonth == 2 && this->day == 29 )
{
this->day = 1;
this->month = 3;
}
}
return *this;
}
myDate nextday=today.nextDay();
cout<<nextday;
1:一个版本是返回值类型是:myDate &
2:还有一个版本返回值的类型是:myDate
问题:
1:这两个版本都能实现递增到下一天的功能,那么在实现功能的情况下,使用哪个版本好?【类成员中没有涉及到动态空间分配的情况】
使用引用的较好:一、是由于少复制一环节,二、毕竟,你修改的是对象本身的成员变量,而不是对象的拷贝,故用this即可。
2:这两个版本的效率哪个高?
不考虑其他,只对比引用和副本,肯定引用效率高。
3:在实现 < <重载的情况下,为什么【cout < < tday.nextDay();】这样的输出不行,而【cout < < tday.nextDay1();】却能实现?
同上,不行的原因是你修改的不是对象本身的成员变量,而是对象副本。在函数外对函数内申明的局部变量的引用是未定义的(栈空间)。
ps:顺便问下一个派生类能继承2个基类?
可以!
myDate myDate::nextDay();
.........
ostream& operator<<( ostream &output, myDate md )
{
output << md.year << "/" << md.month << "/" << md.day << endl;
return output;
}
ostream& operator<<( ostream &output, myDate &md )
{
output << md.year << "/" << md.month << "/" << md.day << endl;
return output;
}