无法从另一个函数访问文件范围变量的内容

Unable to access contents of file-scope variable from another function

本文关键字:变量 范围 文件 访问 另一个 函数      更新时间:2023-10-16

我有2个函数,其中一个是递归的。这是真正的代码:

class Graph {
public:
Graph(int v);
virtual ~Graph();
void addEdge(int v, int w);
/**
* main function that finds and checks SCC
*/
bool checkSCC();
/**
* function that returns reverse (or transpose) of this graph
*/
Graph getTranspose();
private:
int V;
std::list<int> *adj;
std::vector<int> scc;
/**
* fills stack with vertices (in increasing order of finishing times).
* the top element of stack has the maximum finishing time.
*/
void fillOrder(int v, bool visited[], std::stack<int> &stack);
/**
* a recursive function to print DFS starting from v
*/
void DFSUtil(int v, bool visited[]);
};
Graph::Graph(int v) {
this->V = v;
adj = new std::list<int>[v];
}
Graph::~Graph() {
}
void Graph::addEdge(int v, int w) {
adj[v].push_back(w);
}
bool Graph::checkSCC() {
std::stack<int> stack;
bool *visited = new bool[V];
for(int i=0; i<V; i++)
visited[i]=false;
for(int i=0; i<V; i++)
if(visited[i]==false)
fillOrder(i, visited, stack);
Graph gr = getTranspose();
for(int i=0; i<V; i++)
visited[i]=false;
while(stack.empty() == false){
int v = stack.top();
stack.pop();
if(visited[v]==false){
if(scc.size() > 1) { /*NOTE the problem is HERE !*/
return true;
}
gr.DFSUtil(v, visited);
}
}
return false;
}
Graph Graph::getTranspose() {
Graph g(V);
for(int v=0;v<V;v++){
std::list<int>::iterator i;
for(i=adj[v].begin();i!=adj[v].end();++i)
g.adj[*i].push_back(v);
}
return g;
}
void Graph::fillOrder(int v, bool visited[], std::stack<int>& stack) {
visited[v] = true;
std::list<int>::iterator i;
for(i = adj[v].begin(); i!= adj[v].end(); ++i)
if(!visited[*i])
fillOrder(*i, visited, stack);
stack.push(v);
}
void Graph::DFSUtil(int v, bool visited[]) {
visited[v] = true;
scc.push_back(v); /*NOTE scc only works in this function !! */
std::cout << v << " ";
std::list<int>::iterator i;
for(i = adj[v].begin(); i != adj[v].end(); ++i)
if(!visited[*i])
Graph::DFSUtil(*i, visited);
}

在此代码中,如果我调用 Graph::checkSCC,scc 将其内容保留在 Graph::D FSUtil 的范围内,但不在 Graph::checkSCC 中!为什么会这样?

我感谢任何想法和建议。

你在一个对象上调用checkSCC,在另一个对象上调用DFSUtil(gr,你在checkSCC中创建(。

一个成员的scc成员与另一个成员的scc成员没有联系。