Why does subclassing a numeric type break its use as a property of a custom class?
1 次查看(过去 30 天)
显示 更早的评论
I’m seeing some odd behavior while trying to use a subclassed numeric type in a custom class I’m creating. Within the custom class, if I specify a property as a vector of type double, I can specify a default value as a scalar and everything works as expected (it fills the vector with copies of the scalar value if I don’t provide an input). But as soon as I change the type to a subclass of double, such as the ExtendDouble example given in the documentation here, I can no longer use a scalar as the default value, even though the error message itself says I should be able to:
>> testClass([1;2;3])
Error setting default value of property 'param1' of class 'testClass':
Size of default value must match specified dimensions 3×1 or be scalar.
So I have two questions:
1. Why does my code work for double but not ExtendDouble?
2. Why is it even trying to use the default value at all, when I’ve explicitly provided the value as an input argument to the constructor?
My custom class code is as follows:
classdef testClass
properties
param1(3,1) ExtendDouble = 0
end
methods
function self = testClass(param1)
if nargin > 0
self.param1 = param1;
end
end
end
end
0 个评论
采纳的回答
Matt J
2021-3-2
编辑:Matt J
2021-3-3
1. Why does my code work for double but not ExtendDouble?
The ExtendDouble example is old. It's subsasgn() method was not written to properly handle the newer property initialization features. The following modification will fix the issue.
case '()'
newd = subsasgn(double(obj),s(1),double(b));
if isa(b,'ExtendDouble'),
obj = ExtendDouble(newd,b.DataString);
elseif isa(obj,'ExtendDouble')
obj= ExtendDouble(newd,obj.DataString);
end
2. Why is it even trying to use the default value at all, when I’ve explicitly provided the value as an input argument to the constructor?
Constructor functions have special behavior. Within them, an initial version of the output object "self" gets created with default values as soon as the constructor workspace is entered. Therefore, anything you do to self in the body of the testClass() constructor is simply modifying that initial object. It doesn't create it from scratch.
As a simple way to see this, you can test the following simpler class,
classdef myclass
methods
function self = myclass()
disp ' '
whos
end
end
end
Running the constructor shows that self has been created in its workspace, even though I did nothing to put it there:
>> obj=myclass;
Name Size Bytes Class Attributes
self 1x1 0 myclass
7 个评论
更多回答(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!