Declaring a class variable within a class, and using it
2 ビュー (過去 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.
0 件のコメント
採用された回答
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 件のコメント
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で NaNs についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!