Filter löschen
Filter löschen

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

2 Ansichten (letzte 30 Tage)
I have a class that contains method. When I access one of properties, I need to use dot operator as follows:
classdef Robot < handle
function move(obj)
obj.x = obj.x + 1; % how to remove obj.
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.

Akzeptierte Antwort

Steven Lord
Steven Lord am 26 Mai 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)
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.

Weitere Antworten (0)


Mehr zu Robotics finden Sie in Help Center und File Exchange




Community Treasure Hunt

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

Start Hunting!

Translated by