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!