Azzera filtri
Azzera filtri

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

5 visualizzazioni (ultimi 30 giorni)
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 Commenti
Hadar
Hadar il 21 Mar 2018
ohh cool, like in bash terminal.
I get the path:
/home/hadar/MATLAB/R2017b/bin/Visited.m % Visited constructor
Adam
Adam il 21 Mar 2018
So it should be able to see it whether inside or outside of your other class, in that case.

Accedi per commentare.

Risposte (1)

Guillaume
Guillaume il 22 Mar 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 Commento
Hadar
Hadar il 25 Mar 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!

Accedi per commentare.

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by