Objects won't keep member variables

조회 수: 7 (최근 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 CenterFile Exchange에서 Construct 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