为什么在定义子类的时候必须调用超类的构造函数?

时间:2016-10-26 14:34:50

标签: matlab

我一直在努力解决以下问题。我们假设我们有一个超类 super ,它本身是句柄类,而 super 的子类 sub 。以下程序不起作用

super.m

classdef super < handle
    properties
        x
    end

    methods
        function this = super(value)
            this.x = value;
        end
    end
end

sub.m

classdef sub < super
    methods
        function this = sub(value)
             this.x = 2*value;
        end
    end
end

如果我运行sub(1),则会提示

Not enough input arguments.

Error in super (line 8)
            this.x = value;

Error in sub

但是,如果我只是在 sub.m 中将this.x = 2*value更改为this = this@super(2*value),那么现在效果非常好......

我将不时地以不同的方式初始化从超类继承的子类中的一些属性,这就是为什么我感到困惑。在这种情况下,我必须调用超类的构造函数吗?

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:2)

这在the documentation中是明确的:

  

如果没有显式调用超类构造函数   子类构造函数,MATLAB®隐式调用这些构造函数   没有争论。在这种情况下,超类构造函数必须支持   没有参数语法。

功能super.m

classdef super < handle
    properties
        x
    end

    methods
        function this = super(value)
            if nargin ~= 0
                this.x = value;
            end
        end
    end
end
相关问题