When subclassing "double" with new properties, is there an easy way to access the data value?
5 次查看(过去 30 天)
显示 更早的评论
Say I have a class subclassing double, and I want to add a string (Similar to the 'extendDouble' in the documentation). Is there an easy way to access the actual numeric value without the extra properties, particular for reassigning? Or if I want to change the value, will I have to recreate the value as a new member of the class with the new value and the same string?
e.g.
classdef myDouble < double
properties
string
end
methods
function obj = myDouble(s)
% Construct object (simplified)
obj.string = s;
end
end
end
----------
x = myDouble(2,'string')
x =
2 string
x = 3
x =
3 string
0 个评论
采纳的回答
Jeffrey Clark
2022-7-13
编辑:Jeffrey Clark
2022-7-13
Sorry but the subsasgn and subsref will be needed (and maybe numArgumentsFromSubscript) just follow the example given, or use Customize Object Indexing - MATLAB & Simulink (mathworks.com) for MATLAB 2021b+ preferred pattern (but it isn't any easier or closer to what you really want).
It would be easier to not subclass a basic type, just have two properties for the string and numeric. Then when referencing the obj.property you get all the appropriate property functions like sqrt(x.val) and disp(['string is ' x.str]), but x = 3 would have to be done as x.val = 3
0 个评论
更多回答(1 个)
Aaron Kaw
2023-11-6
编辑:Aaron Kaw
2023-11-6
Try
x = myDouble(2,'string')
double(x)
I like to also add the following non-static method to my double subclasses:
function value = double(instance)
value = builtin('double', instance);
end
so that I can do
y = myDouble(2, 'string').double
if I only cared about the double value the class outputed for the particular usage of myDouble.
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!