Simple handle problem (I think)

2 vues (au cours des 30 derniers jours)
Marc-Olivier Labrecque-Goulet
Hi, I'm having trouble understanding how to use handles but I understand the basic principle so I know I should be using them for what I do. I want to make links between 2 objects of the same class. Here is an exemple.
class classA
properties
val1 = classB.empty;
val2 = [0,0];
%here the variable I should probably use handle.
links = classA.empty;
end
%here is how I use it in a script or function :
obj1 = classA;
obj2 = classA;
%I add obj2 to the list of links obj1 is doing and vice versa:
obj1.links=[obj1.links,obj2];
obj2.links=[obj2.links,obj1];
I guess links could be an object type handle but I have no clue how I should write it, and how to set it.

Réponse acceptée

Sebastian Castro
Sebastian Castro le 17 Avr 2017
Modifié(e) : Sebastian Castro le 17 Avr 2017
This should work, with the exception that classes in MATLAB are by default "value classes". This means that when you say
obj1.links=[obj1.links,obj2];
and then refer to obj1.links(1) (assuming it was previously empty), you're actually referring to a copy of obj2 instead of obj2 itself.
To declare a class as a handle class, i.e., passed by reference, change the first line of your class definition to inherit from the handle superclass:
classdef classA < handle
- Sebastian
  1 commentaire
Marc-Olivier Labrecque-Goulet
So, that mean I can change properties values of obj2 by calling obj1.links(1)? wow I wasnt expecting that to be that easy!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Function Handles dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by