operator overloading: class*number vs number*class

조회 수: 1 (최근 30일)
Javier Ros
Javier Ros 2018년 8월 29일
댓글: Steven Lord 2018년 8월 29일
Hello,
I've defined a class (lets say vector) and I want to be able to overload the following binary operations
1) >> my_class*number
2) >> number*my_class
I have overloaded mtimes, and then case 1) works (I detect the type of the second operator and proceed accordingly), but case 2) does not. In fact the mtimes function of the class does not get called in case 2).
This may seem as logical, but in cannot figure out a work arround for 2).
How do I program behavior for case 2), that is number*my_class ?.
Thanks,
Javier

채택된 답변

Javier Ros
Javier Ros 2018년 8월 29일
Solution:
It seems that it is a question of object precedence when invoking the mtimes defined operator.
Changing the definition of my_Class from
classdef my_Class
to
classdef (InferiorClasses = {?sym}) my_Class
gives precedence to my_Class mtimes method against the one of sym class
  댓글 수: 1
Steven Lord
Steven Lord 2018년 8월 29일
That is correct. See the first section on this documentation page for an explanation.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Javier Ros
Javier Ros 2018년 8월 29일
편집: Javier Ros 2018년 8월 29일
After some more trials I presume this is a BUG related to the symbolic toolbox.
If I do
2.1) >> 5*my_class ---->>>> WORKS it enters the overloaded class function mtimes
2.2) >> syms g real, g*my_class --->>>> FAILS it does not enter the class function mtimes
The error is:
>> g*ez %g is syms g real, and ez is of type my_class
Error using sym>tomupad (line 1229)
Unable to convert 'my_class' to 'sym'.
Error in sym (line 211)
S.s = tomupad(x);
Error in sym/privResolveArgs (line 966)
argout{k} = sym(arg);
Error in sym/privBinaryOp (line 990)
args = privResolveArgs(A, B);
Error in * (line 312)
X = privBinaryOp(A, B, 'symobj::mtimes');
  댓글 수: 1
Steven Lord
Steven Lord 2018년 8월 29일
No, this is not a bug.
I assume you posted this answer before posting the one that you ultimately accepted, as in the accepted answer you successfully identified how to obtain the behavior you wanted. The comment I posted to that accepted answer points to the documentation page that explains why you see this behavior.

댓글을 달려면 로그인하십시오.

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by