Borrar filtros
Borrar filtros

OOP- instantiate a class within a method of a different class

4 visualizaciones (últimos 30 días)
Hadar
Hadar el 20 de Mzo. de 2018
Comentada: Hadar el 25 de Mzo. de 2018
Hi, I have 2 class files, both stored under the same folder. I want to instantiate class A in one of the method of class B but I get an error message: Undefined function or variable 'A'. how can "connect" between the 2 class files so that they know each other? Thanks!
  8 comentarios
Hadar
Hadar el 21 de Mzo. de 2018
ohh cool, like in bash terminal.
I get the path:
/home/hadar/MATLAB/R2017b/bin/Visited.m % Visited constructor
Adam
Adam el 21 de Mzo. de 2018
So it should be able to see it whether inside or outside of your other class, in that case.

Iniciar sesión para comentar.

Respuestas (1)

Guillaume
Guillaume el 22 de Mzo. de 2018
For somebody coming from C++, I'm surprised you're not using private/public qualifiers for your class methods, rather than having everything public.
The problem with the visited class not being visible is puzzling since which can find it. It's surprising that it is in a bin directory but that doesn't matter.
Irrespective of that issue however, the whole concept of creating a handle class just to emulate a pass-by-reference array is extremely misguided. Matlab is not C++. If you need a mutable object in and out of a function, then you pass it as input and output. Therefore, the proper way to write your DFS would be:
methods
%... constructor, etc.
%DFS method. Note: I prefer calling the object 'this' rather than 'obj'
function DFS(this)
visited_size = this.nodes_num + 1;
visited = zeros(1, visited_size);
for i = 1:this.nodes_num
if visited(i) == 0
visited = DFSutil(this, i, visited);
end
end
end
end
methods (Access = private)
function visited = DFSutil(this, start, visited)
disp(start)
visited(start) = 1;
for i = drange(1:numel(this.vector_of_adj{start}))
if visited(this.vector_of_adj{start}(i)) == 0
visited = DFSutil(this, this.vector_of_adj{start}(i), visited);
end
end
end
end
Note that in the above case, matlab's JIT compiler should be able to detect that input and output are the same and pass the visited array by reference anyway.
  1 comentario
Hadar
Hadar el 25 de Mzo. de 2018
Hi, I'm familiar with public/private qualifiers in c++ and know this option exists in matlab too. I'm new in matlab, therefore less familiar with its syntax but during learning I intend to add these qualifiers to my classes in addition to pass visited as input and output just like adam previously suggested.
Now Visited class is visible and I have no problem to instantiate it. Regarding bin directory, Ive erroneously saved it there.
Thank you for your help!

Iniciar sesión para comentar.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by