神刀安全网

C++ Object Method Chaining

You might see some method chainning usage in JQuery like this:

$('#obj').animate(a).slideUp(b).fadeOut(c);
$('#obj').animate(a).slideUp(b).fadeOut(c);

Actually, this is very simple to implement, all we need to do is to return the object itself as a pointer rather than void type.

class Price {     private:         int v;     public:         Price(int _v) {             v = _v;         }           Price* Raise(int offset) {             v += offset;             return this; // return this object for next chainning method         }           Price* Drop(int offset) {             v -= offset;             return this;// return this object for next chainning method         }           Price Print() {             cout << v << endl;         } };
class Price {     private:         int v;     public:         Price(int _v) {             v = _v;         }          Price* Raise(int offset) {             v += offset;             return this; // return this object for next chainning method         }          Price* Drop(int offset) {             v -= offset;             return this;// return this object for next chainning method         }          Price Print() {             cout << v << endl;         } };

So after modification of internal attributes, we return this , which can be used to chain the next method.

Price x(10); x.Raise(200)->Drop(50)->Print();
Price x(10); x.Raise(200)->Drop(50)->Print();

The above example usage prints 160. Because we initialize the price to 10 and increment 200 and drop 50. This will make your code much cleaner and is a goodOOP (Object Oriented) design principle.

–EOF–

GD Star Rating

loading…

203 words

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » C++ Object Method Chaining

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址