问题描述
我有以下类接口:
class Time
{
public:
Time( int = 0, int = 0, int = 0 );
Time &setHour( int );
Time &setMinute( int );
Time &setSecond( int );
private:
int hour;
int minute;
int second;
};
实现在这里:
Time &Time::setHour( int h )
{
hour = ( h >= 0 && h < 24 ) ? h : 0;
return *this;
}
Time &Time::setMinute( int m )
{
minute = ( m >= 0 && m < 60 ) ? m : 0;
return *this;
}
Time &Time::setSecond( int s )
{
second = ( s >= 0 && s < 60 ) ? s : 0;
return *this;
}
在我的主要.cpp文件中,我有这样的代码:
In my main .cpp file, I have this code:
int main()
{
Time t;
t.setHour( 18 ).setMinute( 30 ).setSecond( 22 );
return 0;
}
如何将这些函数调用链接起来?我不明白为什么会这样。
How is it possible to chain these function calls together? I don't understand why this works.
推荐答案
t的每个方法都会返回 。引用是别名。所以如果你做了
Each of t's methods return a reference to t. A reference is an alias. So if you did
Time t;
Time& tAgain = t;
tAgain.setMinute( 30 );
tAgain.setMinute
也会更改t的时间。
tAgain.setMinute
also alters t's time.
现在推断这个简单的例子来级联。每个t的方法返回一个对自身的引用
Now extrapolate that simple example to cascading. Each method of t returns a reference to itself
Time &Time::setSecond( int s )
{
second = ( s >= 0 && s < 60 ) ? s : 0;
return *this;
}
所以在表达式中:
t.setHour( 18 ).setMinute( 30 )
t.setHour(18)
调用setHour on t,然后返回对t的引用。在这种情况下,引用是临时的。所以你可以认为它就像在评估setHour时上面的行改变为以下行:
t.setHour( 18 )
calls setHour on t, then returns a reference to t. In this case the reference is temporary. So you can think of it as if the above line changed to the following on evaluating setHour:
tAgain.setMinute(30);
t.setHour返回一个引用 - 类似于上面的tAgain。只是t本身的别名。
t.setHour returned a reference -- similar to our tAgain above. Just an alias for t itself.
这篇关于如何“这个”级联工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!