Objects won't keep member variables

5 ビュー (過去 30 日間)
Tilman
Tilman 2012 年 8 月 15 日
コメント済み: Jixiong Su 2023 年 11 月 2 日
Hello. I have a container class that holds an array 'arr' to store instances of the item class. The item class has to member variables called variable1 and variable2.
classdef container
properties
arr;
end
methods
function this = container(n)
this.arr = item.empty(n,0);
for i = 1:n
this.arr(i) = item(4); %set value1 to 4
end
end
end
end
%------------------------------------------------------
classdef item
properties
value1;
value2;
end
methods
function this = item(v)
this.value1 = v;
end
function setValue2(this, v)
this.value2 = v;
end
end
end
%------------------------------------------------------
clear all;
c = container(2);%container able to hold 2 item objects
c.arr(1).setValue2(9); %set value2 of first item to 9
c.arr(1).value1 %display value1 and value2 of first item
c.arr(1).value2
Wenn I run the last part I get this result:
ans = 4
ans = []
So value1 is set correctly in the Constructor, whereas value2 is set via a seperate function called setValue2. When I debug I can see that setValue2(9) sets value2 to 9 but when I leave the function value2 becomes an empty double again.
What am I doing wrong? Why doesnt Matlab keep the value? Do I use item.empty() the wrongt way? I didn't find any other option to declare an empty array of type 'item'.
Tanks you for every answer.

採用された回答

Titus Edelhofer
Titus Edelhofer 2012 年 8 月 15 日
Hi,
the way you write the code is correct, if you have "handle-semantics". For value semantics you have to return the changed object (think of the methods as usual matlab functions), so:
function this = setValue2(this, v)
this.value2 = v;
end
and call like
c.arr(1) = c.arr(1).setValue2(9);
If you don't like this, change your class to be a "handle" class by changing only the definition:
classdef item < handle
Then you c.arr(1) is not the object itself but a reference to the object.
Titus
  3 件のコメント
Joseph
Joseph 2015 年 2 月 16 日
Thank you!! This was frustrating me for awhile.
Jixiong Su
Jixiong Su 2023 年 11 月 2 日
Thanks a lot!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeConstruct and Work with Object Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by