Effacer les filtres
Effacer les filtres

overloading elementary operations on custom classes

1 vue (au cours des 30 derniers jours)
J. Alex Lee
J. Alex Lee le 23 Juil 2018
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)"

Réponses (0)

Catégories

En savoir plus sur Historical Contests dans Help Center et File Exchange

Produits


Version

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by