Objects won't keep member variables

16 次查看(过去 30 天)
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

更多回答(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