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

3 visualizzazioni (ultimi 30 giorni)
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.

Risposta accettata

Steven Lord
Steven Lord il 26 Mag 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?
  • 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

Più risposte (0)

Prodotti


Release

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by