【问题标题】:Vary number of inputs for superclass改变超类的输入数量
【发布时间】:2015-03-05 20:24:00
【问题描述】:

B 是 A 的子类。我想用两个参数调用 B,如 B(arg1, arg2) 并在 B 的构造函数中将 arg1 传递给 A。代码如下所示:

classdef A
properties
    arg1;
end
methods
    function a = A(arg1)
        if nargin > 0
            a.arg1 = arg1;
        end
    end
end    
end

classdef B < A  
properties
    arg2
end   
methods
    function b = B(arg1, arg2)
        b@A(arg1);
        if nargin > 0
            b.arg2 = arg2;
        end
    end
end 
end

到目前为止,一切都很好。现在,有时我想不带参数调用 B(例如初始化数组)。显然调用 B() 会引发错误,输入不足。也禁止在条件内调用 As 构造函数。

有没有什么标准的方法来解决这个问题,基本上是能够调用带有 0 和 n 参数的子类?

干杯

【问题讨论】:

    标签: matlab oop inheritance constructor


    【解决方案1】:

    使用varargin

    classdef B < A  
    properties
        arg2
    end   
    methods
        function b = B(varargin)
            %pass all but the last argument to the super constructor
            b@A(varargin{1:nargin-1});
            if nargin > 0
                b.arg2 = varargin{2};
            end
        end
    end 
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-27
      相关资源
      最近更新 更多