重载八度函数

Overloading Octave Functions

我对 Octave 比较陌生,刚开始使用 classes。我有一个 class 和以下形式的构造函数:

classdef MyClass < handle
properties
  property1
  property2
endproperties
methods
  function self = MyClass(Param1) % Constructor
    self.property1 = Param1;
    self.property2 = "SOMEVALUE"
  endfunction
endmethods
endclassdef

现在我想通过重载构造函数来容纳其他参数,所以我尝试使用以下形式:

classdef MyClass < handle  
properties
  property1
  property2
endproperties
methods
  function self = MyClass(Param1) % Constructor
    self = self.MyClass(Param1, "SOMEVALUE")
  endfunction

  function self = MyClass(Param1, Param2) % Constructor
    self.property1 = Param1;
    self.property2 = Param2;
  endfunction
endmethods
endclassdef

使用这种格式,我收到一个错误:

error: 'Param2' undefined near line x column y

我不确定如何进行。 Octave 文档有一个模糊的示例,几乎没有解释如何重载函数。

显然我在工作时考虑了错误的范例。任何建议或好的资源将不胜感激。 :)

使用参数检查函数

说明

要创建重载函数的效果,您必须明确检查参数的数量和类型,并以编程方式对参数的数量和类型做出反应。没有直接的方法来重载八度音程中的 class 成员(目前)。在您的示例中,您将使用默认参数的八度实现。

简单的解决方案

这个非常简单的解决方案只检查参数的数量,如果第二个参数不存在,则将其设置为默认值。

classdef myClass < handle  

  properties
    property1
    property2
  endproperties

  methods
    function self = myClass(Param1, Param2) % Constructor
      if nargin < 2
        Param2 = "SOMEVALUE";
      endif
      self.property1 = Param1;
      self.property2 = Param2;
    endfunction
  endmethods

endclassdef

示例输出

>> a=myClass(1)
a =

<object myClass>

>> a.property1
ans =  1
>> a.property2
ans = SOMEVALUE

更复杂的解决方案

对于更复杂的重载,我建议使用 variable length argument list with varargin in combination with an inputParser 对象。

避免超载

由于对函数重载提供的最小支持八度,我建议尽可能避免重载