【问题标题】:invoking superclass constructor调用超类构造函数
【发布时间】:2013-07-19 05:23:39
【问题描述】:

我阅读了this documentation page 关于如何从子类调用超类构造函数的信息。他们提到的语法是这样的:

obj = obj@MySuperClass(SuperClassArguments);

我想知道上述语法中@ 符号的用途是什么。 @ 符号是否只是语法中无意义的占位符 @ 符号是否代表 MATLAB 中的 function handle symbol

如果我使用:

obj = MySuperClass(SuperClassArguments); 

而不是

obj = obj@MySuperClass(SuperClassArguments);

它仍然可以正常工作。那么使用@符号的目的是什么?

【问题讨论】:

  • 我实际上没有意识到您链接了函数句柄文档。但是@字符肯定代表函数句柄。
  • 哎呀。谁组成了这些语法? MathWorks 中没有人负责保持语言的一致性吗?

标签: matlab oop constructor superclass matlab-class


【解决方案1】:

1) 不,这与function handles 无关,这是用于call the superclass constructor 的语法

2) 你可以自己试试看。这是一个例子:

上午

classdef A < handle
    properties
        a = 1
    end
    methods
        function obj = A()
            disp('A ctor')
        end
    end
end

B.m

classdef B < A
    properties
        b = 2
    end
    methods
        function obj = B()
            obj = obj@A();        %# correct way
            %#obj = A();          %# wrong way
            disp('B ctor')
        end
    end
end

使用正确的语法,我们得到:

>> b = B()
A ctor
B ctor
b = 
  B with properties:

    b: 2
    a: 1

如果您使用注释行而不是第一行,则会收到以下错误:

>> clear classes
>> b = B()
A ctor
A ctor
B ctor
When constructing an instance of class 'B', the constructor must preserve the class of the returned
object.
Error in B (line 8)
            disp('B ctor') 

【讨论】:

    猜你喜欢
    • 2013-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-08
    • 1970-01-01
    • 2015-01-05
    • 2015-12-18
    相关资源
    最近更新 更多