Declaring a class variable within a class, and using it

15 次查看(过去 30 天)
%% 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 中查找有关 Class File Organization 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by