Why do some Matlab class methods require “apparently” unnecessary output argument

前端 未结 1 1956
暖寄归人
暖寄归人 2021-01-19 12:42

After evolving my project code for months, I\'ve finally hit a need to define a new class. Having to romp through my previous class definitions as a refresher of the conven

1条回答
  •  -上瘾入骨i
    2021-01-19 12:45

    The best place to start is the documentation "Comparison of Handle and Value Classes". From the very top:

    A value class constructor returns an object that is associated with the variable to which it is assigned. If you reassign this variable, MATLAB® creates an independent copy of the original object. If you pass this variable to a function to modify it, the function must return the modified object as an output argument.

    A handle class constructor returns a handle object that is a reference to the object created. You can assign the handle object to multiple variables or pass it to functions without causing MATLAB to make a copy of the original object. A function that modifies a handle object passed as an input argument does not need to return the object.

    In other words, value classes need to return a modified object (which is a new object distinct from the original), while handle classes don't. The constructor of either class will always have to return an object, since it is actually constructing it.

    Some good additional reading is "Which Kind of Class to Use", which links to a couple helpful examples of each type of class object. Looking at the DocPolynom value class example, you can see that property set methods have to return the modified object, while the dlnode handle class example only requires an output for its constructor. Note that you could still return an object from a handle class method (if desired), but it's not required.

    0 讨论(0)
提交回复
热议问题