Class property automatically propagated to old class instances

조회 수: 6 (최근 30일)
Luuk Spin
Luuk Spin 2022년 1월 15일
댓글: Luuk Spin 2022년 1월 18일
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!

채택된 답변

per isakson
per isakson 2022년 1월 18일
편집: per isakson 2022년 1월 18일
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
Luuk Spin
Luuk Spin 2022년 1월 18일
Thanks a lot! Indeed the class inherited properties from a superclass that inherited the handle class. I changed the superclass and now it works :)

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Construct and Work with Object Arrays에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by