필터 지우기
필터 지우기

Declaring a class variable within a class, and using it

조회 수: 10 (최근 30일)
se chss
se chss 2023년 7월 5일
편집: Abhishek 2023년 7월 5일
%% main code
for aa = 1:2
Aclass(aa) = A;
end
for aa = 1:2
Aclass(aa).Dosumthing(aa);
end
%% class A define
classdef A < handle
properties
Bclass = B
end
function Dosumthing(obj, inputs)
Bclass.varis = inputs;
end
end
%% class B define
classdef B < handle
properties
varis = 0;
end
end
The value of Aclass(2).Bclass.varis became 2 even before the value of the for statement variable aa reached 2 by setting the breakpoint. Why?
I want the class variables of Class A to be independent.

채택된 답변

Abhishek
Abhishek 2023년 7월 5일
편집: Abhishek 2023년 7월 5일
Hi se chss ,
As per my understanding I think that your problem is that the value of Aclass(2).Bclass.varis became 2 even before the value of the for statement variable aa reached 2.
In the code which you shared, the issue is that you assigned the same instance of class B to the BClass property of both Aclass(1) and Aclass(2). Because of this they refer to the same instance of class B, resulting in shared properties.
In order to maintain that class variables of class A are independent, you need to have separate instances of class B for each instance of class A. You can look into the following code to achieve this :
%% main code
for aa = 1:2
Aclass(aa) = A;
end
for aa = 1:2
Aclass(aa).Dosumthing(aa);
end
%% class A define
classdef A < handle
properties
Bclass
end
methods
function obj = A()
obj.Bclass = B(); % Create a new instance of class B for each instance of class A
end
function Dosumthing(obj, inputs)
obj.Bclass.varis = inputs;
end
end
end
%% class B define
classdef B < handle
properties
varis = 0;
end
end
In this updated code the constructor of class A is modified to create a new instance of class B for each instance of class A.
By making the changes as told above, class variable of class A will be independent.
You can refer following documentation page for constructor method :

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 NaNs에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by