use*_*888 1 oop matlab constructor superclass matlab-class
我阅读了此文档页面,了解如何从子类调用超类构造函数.他们提到的语法是这样的:
obj = obj@MySuperClass(SuperClassArguments);
Run Code Online (Sandbox Code Playgroud)
我想知道@上面语法中符号的用途是什么.是@符号只是一个毫无意义的地方占用人在语法或没有的@符号代表的功能手柄符号在MATLAB?
如果我使用:
obj = MySuperClass(SuperClassArguments);
Run Code Online (Sandbox Code Playgroud)
代替
obj = obj@MySuperClass(SuperClassArguments);
Run Code Online (Sandbox Code Playgroud)
它仍然可以正常工作.那么使用@符号的目的是什么?
2)你可以尝试一下,亲眼看看.这是一个例子:
classdef A < handle
properties
a = 1
end
methods
function obj = A()
disp('A ctor')
end
end
end
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
使用正确的语法,我们得到:
>> b = B()
A ctor
B ctor
b =
B with properties:
b: 2
a: 1
Run Code Online (Sandbox Code Playgroud)
如果您使用注释行而不是第一行,则会收到以下错误:
>> 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')
Run Code Online (Sandbox Code Playgroud)