Note that the following matlab documentation pages are related, but do not provide an answer to my question (at least not to me): Subclasses of Built-In Types with Properties Subclasses of MATLAB Built-In Types
How to create a subclass to built-in class?
5 次查看(过去 30 天)
显示 更早的评论
I fail to create a subclass to the built-in class ss (state space system, part of control systems toolbox). The constructor for the class, which involves a call to the superclass constructor, returns an instance. This instance has the method 'new_method' in that the methods() function lists it, but when I call the method on the instance, it is not found by the interpreter Here is a very short version of a code that generates the described problem:
classdef my_subclass < ss
properties
my_prop
end
methods
function obj= my_subclass(the_value)
% Constructor.
obj= obj@ss(); % call to superclass constructor not required,
% but makes code clearer
obj.my_prop= the_value;
end
function obj= new_method(obj, the_value)
% Simple example for a method that exists according to the
% methods() function, but cannot be called.
obj.my_prop= the_value;
end
end
end
Instantiation works fine:
>> instance= my_subclass(3)
instance =
Empty state-space model.
>> instance.my_prop
ans =
3
>>
The new method exists:
>> methods(instance)
Methods for class my_subclass:
... new_method % The result of methods is too long to show it here, but it does contain 'new_method'.
Calling 'new_method' results in an error:
>> instance.new_method(4)
Error using InputOutputModel/subsref (line 44)
No property of the class "my_subclass" matches the string "new_method". Use PROPERTIES to get the list of properties for this class.
>>
回答(1 个)
Philip Borghesani
2017-2-21
You did it correctly in general but the ss class should probably be marked as Sealed, I recommend not subclassing it. Only properties of an ss class and its children can be accessed with dot indexing, to call a method use a direct method call:
% instance.new_method(4) % will fail
new_method(instance,4) % correctly calls new_method
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Construct and Work with Object Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!