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!