How to avoid the dot operator when accessing property inside class method

조회 수: 1 (최근 30일)
I have a class that contains method. When I access one of properties, I need to use dot operator as follows:
classdef Robot < handle
properties
x
end
function move(obj)
obj.x = obj.x + 1; % how to remove obj.
end
end
As you can see, using obj. with equation that contains alot of properites is not readable. How to avoid this issue as the case in C++. I think it should be default to refer to properties.

채택된 답변

Steven Lord
Steven Lord 2021년 5월 26일
You don't, at least not the way you're asking.
Suppose you had a different method of your Robot class:
function y = battle(a, b)
end
To what would the "naked" variable x refer in that method?
  • Should it always refer to the x property of the object stored in a? That would throw an error if you called the method like battle(1, RobotInstance) since in that case a would not be a Robot.
  • Should it always refer to the x property of the object stored in b? Same problem just with battle(RobotInstance, 1).
  • But let's say the battle method could only be called with two Robot instances. To what should x refer, a.x or b.x?
One way to avoid having to reference the property repeatedly would be to reference the property once and store its value in a local variable.
function y = battle(a, b)
% Let's assume both a and b are instances of the Robot class.
%
% % If they were numbers we could call the constructor here to
% turn them into Robot objects before trying to use them.
ax = a.x;
bx = b.x;
% Now work with ax and bx instead of a.x and b.x.
end

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Robotics에 대해 자세히 알아보기

태그

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by