首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

一个函数调用的疑惑解决方法

2012-02-26 
一个函数调用的疑惑今天看一个程序时,其中有这么一段代码:time1.setHour(12).setMinute.(32).second(32)

一个函数调用的疑惑
今天看一个程序时,其中有这么一段代码:
time1.setHour(12).setMinute.(32).second(32);
其中time1是一个time   class的对象,而三个函数定义的开头是:
Time&   Time::setHour(int   h)
{}
Time&   Time::setHour(int   m)
{}
Time&   Time::setHour(int   s)
{}
还有一个这样的一个构造函数Time::Time(const   Time&   t)
                                                    {   hour=12;
                                                        minute=t.minute;
                                                        second=t.second+1;
                                                        count++;
                                                      }
我以前没见过这么连续调用函数用这种格式,也没发现例子,能否解释,或者哪书上有解释啊!

[解决办法]
函数返回的是对象,继续调用对象上的方法。

cout < < "1 " < < "2 " < <endl; 一样
[解决办法]
adlay 正解
[解决办法]
#include <iostream>
using namespace std;

class Time
{
public:
Time(void)
{
hour = 0;
minute = 0;
second = 0;
}
Time(const Time& t);
Time& setTimeHour(Time time1, int h);
Time& setMinute(Time time1, int m);
Time& setSecond(Time time1, int s);
void DisplayTime(Time t);
private:
int hour, minute, second;
static int count;
};

Time::Time(const Time& t)
{
hour=12;
minute=t.minute;
second=t.second+1;
count++;
}

Time& Time::setTimeHour(Time time1, int h)
{
time1.hour = h;
return time1;
}

Time& Time::setMinute(Time time1, int m)
{
time1.minute = m;
return time1;
}

Time& Time::setSecond(Time time1, int s)
{
time1.second = s;
return time1;
}

void Time::DisplayTime(Time t)
{
cout < < t.hour < < ": " < < t.minute < < ": " < < t.second < < ": " < <count < <endl;
}

int Time::count = 0;

int main(int argc, char *argv[])
{
Time time1,time2,time3;
time2.setTimeHour (time1, 10).setMinute (time1, 20).setSecond (time1,5);
time3.DisplayTime (time1);
return 0;
}
[解决办法]
和连续复制的道理一样

Obeject &operator=(const Obeject &)

这个你可以看 < <effective c++> >
[解决办法]
cout, cin就是最好的例子了, 其实也没什么的,因为没个函数的返回类型都是time类对象的引用,就相当于调用一个time对象的函数一样。

热点排行