Returning *this in member functions

后端 未结 9 1295
无人共我
无人共我 2020-12-18 22:35

I recently used a library that allows the following type of syntax:

MyClass myObject;
myObject
    .setMember1(\"string value\")
    .setMember2(4.0f)
    .s         


        
9条回答
  •  无人及你
    2020-12-18 23:29

    This is sometimes referred to as the Named Parameter Idiom or method chaining. This isn't bad practice, it can aid readability. Consider this example lifted from the C++ FAQ

    File f = OpenFile("foo.txt")
                .readonly()
                .createIfNotExist()
                .appendWhenWriting()
                .blockSize(1024)
                .unbuffered()
                .exclusiveAccess();
    

    The alternative would be to use positional arguments to the OpenFile method, requiring the programmer to remember the position of each argument.

提交回复
热议问题