如何在运行时使用构造函数初始化类中私有的数组

How to initialize an array that is private in a class using constructor at runtime?

本文关键字:数组 初始化 构造函数 运行时      更新时间:2023-10-16

当我在名为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的数组的内容)

我已经创建了一个Graph类。

是的。

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;

在构造函数中,用适当的零值来填充它。