返回语句后的超类matlab构造函数

时间:2018-04-16 22:55:46

标签: matlab return subclass superclass

我试图在实例化超类的子类时检查某个参数是否属于某种类型,并且我一直收到一个错误,该错误似乎与我检查参数类型的方法有关。调试器甚至不会让我包含一个断点而不会抛出错误A constructor call to superclass appears after the object is used, or after a return.我认为很明显什么行代码会破坏我的类,但为什么我不允许这样做类型检查?还有哪些方法可以确认我的论点属于特定类型?代码如下。

classdef superClass < handle
      properties
          PropertyOne
          PropertyTwo
      end    
      methods
          function sup = superClass(param1, param2)
              sup.PropertyOne = param1;
              sup.PropertyTwo = param2;
          end
      end
end
classdef subClass < superClass
      properties
          PropertyThree
      end   
      methods
          function sub = subClass(param1, param2, param3)
              if ~isa(param1, 'char')
                  disp('param1 must be type char')
                  return
              end
              sub@superClass(param1, param2);
              sub.PropertyThree = param3;        
          end
      end
end

1 个答案:

答案 0 :(得分:0)

像这样实施subClass

classdef subClass < superClass
      properties
          PropertyThree
      end   
      methods
          function sub = subClass(param1, param2, param3)
              assert(ischar(param1),'param1 must be type char')
              sub@superClass(param1, param2);
              sub.PropertyThree = param3;        
          end
      end
end

在超类构造函数运行之前,您不能拥有return语句。 return需要使用sub的输出退出函数,并且在超类构造函数运行之前sub不存在。如果您使用assert(或者您可以将iferror一起使用,但assert更简单),那么它将退出而不会输出sub ,所以没关系。

另请注意,您不需要isa(..., 'char'),只需使用ischar