When I have nested objects, changing the parameter of one object changes the same parameter in others
조회 수: 2 (최근 30일)
이전 댓글 표시
MathWorks Support Team
2019년 1월 3일
편집: MathWorks Support Team
2022년 10월 13일
I am working with two handle classes, Class1 and Class2, defined as follows:
classdef Class1 < handle
properties
a = Class2;
end
end
classdef Class2 < handle
properties
b = 1;
end
end
If I create two separate instances of Class1 and adjust the value of parameter 'b' in the nested instance of Class2, the value of 'b' in both instances of Class 1 change. Is this supposed to happen?
채택된 답변
MathWorks Support Team
2022년 10월 13일
편집: MathWorks Support Team
2022년 10월 13일
This is an intended behavior for handle classes, and is documented here:
When a constructor for a handle class is placed in the 'properties' section of a class definition, MATLAB creates one generic object of that class and makes the property a handle to that object. If multiple constructors for the same class appear in the 'properties' section, or if multiple objects are created that have the same constructor in their 'properties', a handle to that same generic object are assigned to those properties. In other words, MATLAB does not create a new object every time the constructor is called in the properties section, instead it creates one object and links every constructor call to it.
This behavior can be eliminated by moving the constructor call from the properties section to the constructor of the object. For example, Class1 in the questions can be changed to:
classdef Class1 < handle
properties
a;
end
methods
function obj = Class1()
obj.a = Class2();
end
end
end
댓글 수: 0
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Class Introspection and Metadata에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!