为什么我收到错误 "the constructor must preserve the class of the returned object"?

Why am I getting the error "the constructor must preserve the class of the returned object"?

总的来说,我对我的 OOP 概念有点生疏,我仍在学习 MATLAB 的 OOP 实现细节。我有一个从超类继承的子类。我按照 MATLAB 的语法规则调用超类构造函数,如下所示:

obj = obj@MySuperClass(SuperClassArguments);

我检查了其他类似的问题,但我似乎遗漏了一些东西,因为除了我需要使用子类 属性 调用超类构造函数。

subClass.m 文件内容:

classdef subClass < superClass
    properties (Access = public)
        arg1 = 1        
    end

    methods
        function obj = subClass(arg1)
            obj = obj@superClass(arg1);
        end
    end
end

superClass.m 文件内容:

classdef superClass
    properties (Access = protected)
        arg2
    end

    methods
        function obj = superClass(local_arg1)
            switch local_arg1
                case 1
                    obj = functionA();
                otherwise
                    obj = functionB();
            end
        end       
    end
end
function obj = functionA(obj)
    obj.arg2 = 1;
end
function obj = functionB(obj)
    obj.arg2 = 2;
end

我正在 MATLAB 命令提示符下创建子类对象,如下所示:

>> a = subClass(1);

我得到错误:

When constructing an instance of class 'subClass', the constructor must preserve the class of the returned object.

任何关于我出错的指示?

问题似乎出在 superClass class 上。当你调用你的函数 functionAfunctionB 时,你需要传递当前对象:

classdef superClass
  properties (Access = protected)
    arg2
  end

  methods
    function obj = superClass(local_arg1)
      switch local_arg1
        case 1
          obj = functionA(obj);
          %Or: obj = obj.functionA();
        otherwise
          obj = functionB(obj);
          %Or: obj = obj.functionB();
      end
    end
  end

  methods (Access = private)
    function obj = functionA(obj)
      obj.arg2 = 1;
    end
    function obj = functionB(obj)
      obj.arg2 = 2;
    end
  end
end

我还建议将这些函数包含在 class 的方法块中(而不是 local functions in the file) as that is the typical format for a single-file class definition. As a local function, I believe they would default to protected/private methods, as they are not visible using methods。另外,将它们放在方法块中允许您使用 obj.functionA() 调用它们的语法,当它们被定义为本地函数时,这显然是不允许的。