"这个"级联如何工作?

tea*_*her 5 c++ this

我有以下类接口:

  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; 
  }; 
Run Code Online (Sandbox Code Playgroud)

实施在这里:

  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; 
   }
Run Code Online (Sandbox Code Playgroud)

在我的主.cpp文件中,我有这个代码:

int main()
{
    Time t;     
    t.setHour( 18 ).setMinute( 30 ).setSecond( 22 );
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

如何将这些函数调用链接在一起?我不明白为什么会这样.

tem*_*def 14

这种方法正常工作的原因是你打电话的时候

t.setHour( 18 )
Run Code Online (Sandbox Code Playgroud)

返回值是a Time&,Time对象的引用.更重要的是,它被定义为

Time &Time::setHour( int h ) 
{
   hour = ( h >= 0 && h < 24 ) ? h : 0; 
   return *this;  // <--- right here
}
Run Code Online (Sandbox Code Playgroud)

在成员函数内部,this是指向进行调用的对象的指针,并且*this是对进行调用的对象(接收者对象)的引用.这意味着当您调用时setHour,该函数会设置时间的小时,然后返回Time对您进行调用的对象的引用.因此,t.setHour( 18 )两者都设置小时,然后返回对接收器对象的引用.那样,你可以写

t.setHour( 18 ).setMinute( 30 ).setSecond( 22 );
Run Code Online (Sandbox Code Playgroud)

因为它被解释为

((t.setHour( 18 )).setMinute( 30 )).setSecond( 22 );
Run Code Online (Sandbox Code Playgroud)

并且在每种情况下函数都返回一个引用t.

更一般地说,只要函数返回引用并且该引用是*this,任何对函数返回值执行的操作都与您在对象本身上执行的操作无法区分.

希望这可以帮助!


Goz*_*Goz 6

由于每个函数都返回对此对象对象的引用(返回*this).

基本上这意味着每次调用函数时都会进行相关更改,然后将整个对象作为参考传回.然后可以对返回的对象进行调用.

它也可以写成如下:

 Time t;
 Time& t1 = t.setHour( 18 ); // t1 will refer to the same object as t.
 Time& t2 = t1.setMinute( 30 ); // t2 will refer to the same object as t1 and t.
 Time& t3 = t2.setSecond( 22 ); // t3 will refer to the same object as t2, t1 and t.
Run Code Online (Sandbox Code Playgroud)

这可能会让您更容易理解正在发生的事情.


Dou*_* T. 6

t的每个方法都返回对t的引用.引用是别名.所以如果你这样做了

 Time t;
 Time& tAgain = t;
 tAgain.setMinute( 30 ); 
Run Code Online (Sandbox Code Playgroud)

tAgain.setMinute 也改变了时间.

现在将这个简单的例子推断为级联.t的每个方法都返回对自身的引用

  Time &Time::setSecond( int s ) 
  {
      second = ( s >= 0 && s < 60 ) ? s : 0; 
      return *this; 
  }
Run Code Online (Sandbox Code Playgroud)

所以在表达式中:

  t.setHour( 18 ).setMinute( 30 )
Run Code Online (Sandbox Code Playgroud)

t.setHour( 18 )在t上调用setHour,然后返回对t的引用.在这种情况下,引用是临时的.因此,您可以将其视为在评估setHour时上面的行更改为以下内容:

  tAgain.setMinute(30);
Run Code Online (Sandbox Code Playgroud)

t.setHour返回了一个引用 - 类似于上面的tAgain.只是t本身的别名.