OOP- instantiate a class within a method of a different class
4 次查看(过去 30 天)
显示 更早的评论
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 个评论
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
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Software Development Tools 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!