필터 지우기
필터 지우기

overloading elementary operations on custom classes

조회 수: 1 (최근 30일)
J. Alex Lee
J. Alex Lee 2018년 7월 23일
I want to encapsulate numbers within a class to hold some meta-information about the number, e.g.
classdef myClass
properties
Value
Meta1
Meta2
end
methods obj = myClass(Value,Meta1,Meta2)
myClass.Value = Value;
myClass.Meta1 = Meta1;
myClass.Meta2 = Meta2;
end
end
and I would like to be able to operate on this class using functions defined for numbers (reals, complex, integers, etc), which the Value property would contain, e.g.:
>> var = myClass(5.2,'Info1','Info2')
>> var+5
ans =
10.2
I understand the following mechanism to intercept specific functions:
methods
function out = plus(A,B)
if isa(A,'myClass')
A = A.Value;
end
if isa(B,'myClass')
B = B.Value;
end
out = builtin('plus',A,B);
end
end
but I wonder if there is a way to intercept all operators so that any time an attempt is made to operate on an object of class 'myClass', it will know to operate only on the Value property of the class? In other words, I don't want to replicate the code above for all functions I would want to be able to use directly on the myClass object, e.g., minus, cos, sign, mldivide.
I also don't want to have to specify the Value property every time, e.g., "cos(var.Value)"

답변 (0개)

카테고리

Help CenterFile Exchange에서 Historical Contests에 대해 자세히 알아보기

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by