How does “this” cascading work?

2019-05-01 15:11发布

I have the following class interface:

  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; 
  }; 

The implementation is here:

  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; 
   }

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.

标签: c++ this
7条回答
唯我独甜
2楼-- · 2019-05-01 16:05

The technique is called method chaining. In the example you've given, all the methods return the same object (this), so they all affect the same object. That's not uncommon, but it's useful to know that it doesn't have to be the case; some or all of the methods in the chain can return different objects. For example, you might also have methods like:

Date Time::date() const;
String Date::dayOfWeek() const;

in which case you could say:

Time t;
String day = t.date().dayOfWeek();

to get the name of day of the week. In that case, t.date() returns a Date object which is used in turn to call dayOfWeek().

查看更多
登录 后发表回答