- 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
5 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Bandar
el 26 de Mayo de 2021
Respondida: Steven Lord
el 26 de Mayo de 2021
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 comentarios
Respuesta aceptada
Steven Lord
el 26 de Mayo de 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 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Robotics en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!