When subclassing "double" with new properties, is there an easy way to access the data value?

6 次查看(过去 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

采纳的回答

Jeffrey Clark
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

更多回答(1 个)

Aaron Kaw
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.

类别

Help CenterFile Exchange 中查找有关 Construct and Work with Object Arrays 的更多信息

产品


版本

R2022a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by