필터 지우기
필터 지우기

Overloading subsasgn results in error when initializing an object array

조회 수: 1 (최근 30일)
B Verhaar
B Verhaar 2017년 8월 17일
답변: Steffen M. 2018년 2월 11일
Good day
I have made a class in which I overload the subsasgn method.
classdef dummyClass
properties
A = [1, 2]
end
%%overload subsasgn
methods
function obj = subsasgn(obj, s, varargin)
% subsasgn is overloaded to incorporate some verifications
%%TODO some verifications
%%execute the assignment
% call the builtin with the same arguments
obj = builtin('subsasgn', obj, s, varargin{:});
%%TODO some more verifications
end
end
end
Then I want to initialize an array of dummyClass objects using the following code
clear all
dummyArray(3, 2) = dummyClass()
This gives the following error message:
Error using subsasgn
The following error occurred converting from dummyClass to double:
Error using double
Conversion to double from dummyClass is not possible.
Error in dummyClass/subsasgn (line 15)
obj = builtin('subsasgn', obj, s, varargin{:});
How can I overload the subsasgn method such that the given assignment does not result in an error?
Kind regards
Boudewijn Verhaar

답변 (2개)

Veda Upadhye
Veda Upadhye 2017년 8월 22일
Hi,
It looks like the overloaded "subsasgn" function is being called on initialization of your "dummyClass" objects. The overloaded function "subsasgn" will need to address this kind of assignment in your code. The documentation below includes a code pattern for such scenarios. You may find it useful to follow a similar pattern.
https://www.mathworks.com/help/matlab/matlab_oop/code-patterns-for-subsref-and-subsasgn-methods.html#bu7rrmd
I hope this helps!
Veda

Steffen M.
Steffen M. 2018년 2월 11일
Hi,
in your case the subsasgn function is called at the beginning with an object from type double. If you insert a constructor call it should work.
function obj = subsasgn(obj, s, varargin)
if isnumeric( obj), obj = dummyClass(); end
% call the builtin with the same arguments
obj = builtin('subsasgn', obj, s, varargin{:});
end
Kind regards Steffen

카테고리

Help CenterFile 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!

Translated by