Declaring a class variable within a class, and using it

14 Ansichten (letzte 30 Tage)
se chss
se chss am 5 Jul. 2023
Bearbeitet: Abhishek am 5 Jul. 2023
%% 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.

Akzeptierte Antwort

Abhishek
Abhishek am 5 Jul. 2023
Bearbeitet: Abhishek am 5 Jul. 2023
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 :

Weitere Antworten (0)

Kategorien

Mehr zu Class File Organization finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by