Matlab类方法既抽象又静态是什么意思?

时间:2015-11-06 20:23:26

标签: matlab oop static abstract

Matlab允许类方法同时为abstractstatic,这与许多OO语言不同。但是,在尝试了几个案例后,我不清楚如何在实际代码中使用它。考虑这个示例抽象类:

classdef (Abstract) TestParent
    methods (Access = public, Abstract = true, Static = true)
        f()
    end

    methods (Access = public, Static = true)
        function g()
            disp('Test g');
            TestParent.f();  % This line will cause problems
        end
    end
end

考虑这个具体的儿童班:

classdef TestChild < TestParent
    methods (Access = public, Static = true)
        function f()
            disp('f child');
        end
    end
end

如对类TestParent的注释中所述,对抽象静态f()的调用将在运行时失败。具体来说,从命令行,使用子类,我得到:

>> TestChild.f()
f child
>> TestChild.g()
Test g
Error using TestParent.f
Method 'f' is not defined for class 'TestParent' or is removed from MATLAB's search path.

Error in TestParent.g (line 13)
    TestParent.f();

在使用父类的命令行中,我得到:

>> TestParent.g()
Test g
Error using TestParent.f
Method 'f' is not defined for class 'TestParent' or is removed from MATLAB's search path.

Error in TestParent.g (line 13)
    TestParent.f();

所以,总结一下:

  • 我可以毫无问题地在子课上调用f。这是有道理的,因为它在子类中有一个具体的实现。到目前为止一切顺利。
  • 如果我尝试使用父类名称作为限定符来调用g,则代码会在需要调用抽象静态方法f时崩溃。这是有道理的,因为父级没有f的实现,并且调用路径没有通过任何具体的孩子。
  • 如果我尝试从子类调用g,它会识别出子类没有具有该名称的本地方法,并转到父类,它找到并尝试运行父类的{ {1}}。在这种情况下,我希望它能够成功运行,因为调用路径在逻辑上意味着应该运行g的具体实现。但它崩溃了。

最后一个对我来说真是一个惊喜。我希望如果静态和抽象意味着什么,那就意味着这是支持的。鉴于这显然不受支持,我无法理解为什么这种关键字组合有意义。任何人都可以为此提供一个用例吗?

0 个答案:

没有答案