开发者

How is this code working?

I am working with the company code and I see this:

ClassName(/* bunch of parameters */)
  .someFunc(/* bunch of parameters */)
  .someFunc(/* bunch of parameters */)
  .someFunc(/* bunch of parameters */)
  ;

开发者_运维百科Now I have never seen this and didn't know something like this could work (the code compiles in the company solution) so I tried it out but I had no such luck. The code failed to compile due to incorrect syntax. I am baffled as to how it is working on the company's solution...? Maybe I am overlooking something?


This technique is called Method Chaining. It basically works by returning a reference to *this in every method that you call. This allows you to directly call another method on the returned object (called chaining).


Huh? What's strange about this? Doesn't this just mean that someFunc() is declared like so:

ClassName& someFunc(/*arguments*/)
{
  /*do stuff*/
  return *this;
}

in order to support chaining? Just like the stream operators?


someObj.someFunc() may return a reference to someObj, like this:

class ClassName {
    ClassName &someFunc() {
        return *this; // return current object, nothing created
    }
};

ClassName someObj;

someObj.someFunc().someFunc(); // chain function calls on same object
ClassName().someFunc().someFunc(); // same, but now object is a temporary

This also works with a direct object return type, as opposed to a reference. In this pattern, the object may be modified at each step.

class ClassName {
    ClassName increment() const {
        return *this + 1; // return a newly created object
    }
};

ClassName someObj;
someObj.increment().increment(); // does not modify someObj, returns temporary

The key to understanding such code always lies in looking at the declaration of the function of interest.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜