当我在名为visited的类中在私有访问中创建一个指针时,我创建了一个类Graph。在构造函数中,我在所有地方都将数组初始化为零,但是当我在另一种方法中检查所有值是否为零时,它在数组中显示垃圾值,但是当我在构造函数本身中打印它时,它显示全为零.
#include<iostream>
#include<vector>
#include<list>
using namespace std;
class Graph {
private:
int vertices,edges;
vector <list<int>> graph;
vector <int> vs;
int *visited;
public:
Graph (int vertices)
{
this->vertices = vertices;
list <int>l;
for (size_t i = 0; i < vertices; i++) {
graph.push_back(l);
vs.push_back(i);
}
edges=0;
// ####### made a new array, initialized all values with zeroes and assigned it to the instance variable visited #########
int a[vertices]={0};
this->visited = a;
// ######## in the constructor it is showing correct values below #######
for (size_t i = 0; i < vertices; i++) {
std::cout << this->visited[i] << ' ';
}
std::cout << '\n';
}
virtual ~Graph ()
{
}
void showList()
{
// just printing the graph in the form of adjacency list
// it is working fine
for (size_t i = 0; i < vertices; i++)
{
list <int>::iterator p = graph[i].begin();
std::cout << i ;
for (; p != graph[i].end() ; p++)
{
std::cout << " -> " << *p ;
}
std::cout << " -> NULL" << '\n';
}
// ######## when I am checking the values here then it is printing garbage values
for (size_t i = 0; i < this->vertices; i++) {
std::cout << this->visited[i] << ' ';
}
}
void addEdge(int source, int destination)
{
graph[source].push_back(destination);
}
};
int main()
{
Graph g(6);
g.addEdge(0,1);
g.addEdge(0,2);
g.addEdge(1,0);
g.addEdge(1,3);
g.addEdge(1,4);
g.addEdge(2,0);
g.addEdge(2,4);
g.showList();
return 0;
}
当我调用 showList 方法时,它应该打印相邻列表和所有零(名为visited 的数组的内容)
我做了一个类图。
是的,你有。
class Graph {
我在名为visited 的类中创建了一个私有访问指针。
是的,你有。
private:
int *visited;
在构造函数中,我在所有地方都用零初始化了数组。
是的,你有。
int a[vertices]={0};
但我会注意到这是一个局部于构造函数的变量。它对任何其他方法都是不可见的。同样,当构造函数完成此对象的生命周期时。任何在其生命周期结束后访问该数组的尝试都是未定义行为。因此,通过某种偷偷摸摸的机制(例如将其地址保存在指针中)访问它会导致不好的事情发生。
在这里,您正在做一些偷偷摸摸的事情(而且非常糟糕):
this->visited = a;
但是当我在另一种方法中检查所有值是否为零时
您正在通过指针访问数组visited
。这指向一个不再存在的数组,因为该数组是另一个函数的本地数组。
std::cout << this->visited[i] << ' '; // This is broken code.
它显示数组中的垃圾值
你太倒霉了。如果程序崩溃并且让坏事正在发生变得更加明显,那就更好了。不幸的是,您发现未定义的行为可以做任何事情(包括简单地返回一些随机值)。
但是当我在构造函数中打印它时,它显示全零。
它在构造函数中仍然有效,因此访问它不是问题。
一般来说,你应该避免使用指针(尤其是全新的)。您需要先了解一些基本概念。
在这种情况下,只需替换:
int* visited;
和
std::vector<int> visited;
在构造函数中用适当的零值填充它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句