如何在运行时使用构造函数初始化类中私有的数组
How to initialize an array that is private in a class using constructor at runtime?
当我在名为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;
在构造函数中,用适当的零值来填充它。
相关文章:
- C++使用整数的压缩数组初始化对象
- C++17中函数模板中的静态数组初始化(MSVC 2019)
- 从另一个静态常量数组初始化静态常量数组(只需少量计算)
- 在 Python 和 c++ 2d 数组初始化之间.这是怎麽?为什么呢?
- 字节数组初始化会导致 DirectX 崩溃
- 使用 new 和 值进行数组初始化,但没有显式数量的元素
- 运行时C++数组初始化问题
- 使用带有参数包的数组的成员数组初始化类
- 仅通过C++中数组初始化的不同方法,即可在同一输入上获得两个不同的答案
- C++ 2 个指针数组初始化 C2440
- C++结构字符数组初始化
- C++中的多维数组初始化
- constexpr数组初始化
- C++引物动态数组初始化程序的数目超过大小
- 使用std::index_sequence对std::数组初始化进行包扩展
- 当 std 数组初始化太小时,C++会引发错误吗?
- 如何确定结构数组初始化的大小?
- Qt并发错误:数组初始化需要大括号括起来的初始值设定项列表
- 此代码中的数组初始化样式是什么?这是标准的吗?
- C++ 使用数组初始化时的 STL 向量内存管理