Why I cannot change the class property in this case?
18 次查看(过去 30 天)
显示 更早的评论
Below is the example code of OBJECTO.m
classdef OBJECTO
properties (Access = private)
pos {mustbevector}
end
methods (Access = public)
function obj = OBJECTO(vec)
% constructor
if nargin < 1
obj.pos = [0, 0, 0];
else
obj.pos = vec
end
end
function obj = setpos(vec)
% set position
obj.pos = vec
end
function vec = getpos(obj)
% get position
vec = obj.pos
disp(vec)
end
end
end
and I made .m file to execute above. (remove ; for the debugging)
function ans = myfunc()
myobject1 = OBJECTO()
myobject1.setpos([100, 0, 0])
tmp = getpos(myobject1)
end
and in consol, typed the above function
myfunc()
the result says
ans =
OBJECTO with properties
pos = [0, 0, 0]
ans =
OBJECTO with properties
pos = [100, 0, 0]
tmp =
0 0 0
that means the instance of OBJECTO (I mean 'myobject1' in the above) value is not changened
I have changed the property pos from 'private' to 'public' but same thing occured
why this happens?
0 个评论
采纳的回答
Matt J
2023-1-16
编辑:Matt J
2023-1-16
You called setpos() without returning anything. So, you need to have,
myobject1 = myobject1.setpos([100, 0, 0])
2 个评论
Walter Roberson
2023-1-17
Why would you write the handler twice?
MATLAB has two types of classes: value objects, and handle objects.
Value objects work like typical MATLAB numeric arrays, where operations on the object do not change the object unless you assign the new value over top of old one. Just like
A = 3;
update_me(A)
A
function update_me(X)
X = X + 1;
end
This does not change the value of A and most people would not expect it to update the value of A.
Handle objects are more like passing around pointers to heap objects, where changes inside the class methods do change everyone's view of the object.
You should implement which-ever of the two makes sense in your situation. You do not need to implement both.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File 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!