- 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?
How to avoid the dot operator when accessing property inside class method
4 views (last 30 days)
Show older comments
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.
0 Comments
Accepted Answer
Steven Lord
on 26 May 2021
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?
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 Comments
More Answers (0)
See Also
Categories
Find more on Robotics in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!