Class property automatically propagated to old class instances

5 vues (au cours des 30 derniers jours)
Luuk Spin
Luuk Spin le 15 Jan 2022
Commenté : Luuk Spin le 18 Jan 2022
Dear matlab user,
I struggle with the following problem I have with my own definition for a class I use. I will illustrate the problem by means of an example. Say I define the following class:
classdef exampleClass
properties
exampleProp double {mustBeFinite(exampleProp)}
end
methods
function obj = exampleClass(exampleProp)
arguments
exampleProp = []
end
obj.exampleProp = exampleProp;
end
end
end
Now I initiate a class instance as follows:
Exmp = exampleClass(1);
I have the following issue when I copy the object.
Exmp1 = exmp;
Exmp2 = exmp;
Exmp1.exampleProp = 5;
What I would like to happen is that Exmp1 is updated and Expm,Expm2 are unchanged. However all objects now have that the exampleProp property is changed to 5. How do assure that I can change a property value without it being propagated to other class instances?
Thanks you very much!

Réponse acceptée

per isakson
per isakson le 18 Jan 2022
Modifié(e) : per isakson le 18 Jan 2022
Your exampleClass is a value class. However, the behavior you describe is more like that of a handle class. See the examples below. (To run the code I need to attach the classdef-files rather than including them in this text.)
%% value class
v = exampleClass(1);
v1 = v
v1 =
exampleClass with properties: exampleProp: 1
v2 = v
v2 =
exampleClass with properties: exampleProp: 1
v1.exampleProp = 5
v1 =
exampleClass with properties: exampleProp: 5
v
v =
exampleClass with properties: exampleProp: 1
v2
v2 =
exampleClass with properties: exampleProp: 1
%% handle class
h = exampleClass_handle(1);
h1 = h
h1 =
exampleClass_handle with properties: exampleProp: 1
h2 = h
h2 =
exampleClass_handle with properties: exampleProp: 1
h1.exampleProp = 5
h1 =
exampleClass_handle with properties: exampleProp: 5
h
h =
exampleClass_handle with properties: exampleProp: 5
h2
h2 =
exampleClass_handle with properties: exampleProp: 5
  1 commentaire
Luuk Spin
Luuk Spin le 18 Jan 2022
Thanks a lot! Indeed the class inherited properties from a superclass that inherited the handle class. I changed the superclass and now it works :)

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Construct and Work with Object Arrays dans Help Center et File Exchange

Produits


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by