フィルターのクリア

Class property automatically propagated to old class instances

2 ビュー (過去 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 Center および File ExchangeConstruct 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