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?

采纳的回答

Matt J
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 个评论
NoYeah
NoYeah 2023-1-17
so if I want to modify some properties of a class, then I have to write handler twice?
Why the matlab choose the most uncomfortable way
Walter Roberson
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
A = 3
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 CenterFile Exchange 中查找有关 Construct and Work with Object Arrays 的更多信息

产品


版本

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by