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

조회 수: 6 (최근 30일)
Hadar
Hadar 2018년 3월 20일
댓글: Hadar 2018년 3월 25일
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
Hadar
Hadar 2018년 3월 21일
ohh cool, like in bash terminal.
I get the path:
/home/hadar/MATLAB/R2017b/bin/Visited.m % Visited constructor
Adam
Adam 2018년 3월 21일
So it should be able to see it whether inside or outside of your other class, in that case.

댓글을 달려면 로그인하십시오.

답변 (1개)

Guillaume
Guillaume 2018년 3월 22일
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
Hadar
Hadar 2018년 3월 25일
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!

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Software Development Tools에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by