C++ 如何在构造函数中初始化struct的动态数组?
这是一个基于深度优先搜索(DFS)结构的动态数组的堆栈类。每当遇到函数push()时,程序无法运行,这表明数组在构造函数中未成功初始化 我试图寻找错误,甚至将struct的动态数组更改为并行数组,但仍然不起作用。我很抱歉,如果问题似乎太简单,无法解决,因为我没有一个坚实的基础,在C++。C++ 如何在构造函数中初始化struct的动态数组?,c++,arrays,data-structures,struct,C++,Arrays,Data Structures,Struct,这是一个基于深度优先搜索(DFS)结构的动态数组的堆栈类。每当遇到函数push()时,程序无法运行,这表明数组在构造函数中未成功初始化 我试图寻找错误,甚至将struct的动态数组更改为并行数组,但仍然不起作用。我很抱歉,如果问题似乎太简单,无法解决,因为我没有一个坚实的基础,在C++。 #include <iostream> #include <iomanip> #ifndef HEADER_H #define HEADER_H using namespace std
#include <iostream>
#include <iomanip>
#ifndef HEADER_H
#define HEADER_H
using namespace std;
struct Value
{
int row; // row number of position
int col; // column number of position
//operator int() const { return row; }
};
class ArrayStack
{
public:
int top;
Value* array;
ArrayStack();
bool isEmpty();
bool isFull();
void push(int r, int c);
void pop();
int poprowvalue(int value);
int popcolvalue(int value);
int peekrow(int pos);
int peekcol(int pos);
int count();
void change(int pos, int value1, int value2);
void display();
void resize();
private:
int size;
};
ArrayStack::ArrayStack()
{
//Initialize all variablies
top = -1;
size = 10;
Value * array = new Value[size];
for (int i = 0; i < size; i++)
{
array[i].row = 0;
array[i].col = 0;
}
}
bool ArrayStack::isEmpty()
{
if (top == -1)
return true;
else
return false;
}
bool ArrayStack::isFull()
{
if (top == size - 1)
return true;
else
return false;
}
void ArrayStack::resize()
{
if (isFull())
size *= 2;
else if (top == size / 4)
size /= 2;
}
void ArrayStack::push(int r, int c)
{
if (isEmpty() == false)
resize();
array[top + 1].row = r;
array[top + 1].col = c;
top++;
}
void ArrayStack::pop()
{
int value;
if (isEmpty())
{
cout << "Stack underflow" << endl;
}
else
{
poprowvalue(array[top].row);
popcolvalue(array[top].col);
array[top].row = 0;
array[top].col = 0;
top--;
}
}
int ArrayStack::poprowvalue(int v)
{
return v;
}
int ArrayStack::popcolvalue(int v)
{
return v;
}
int ArrayStack::peekrow(int pos)
{
if (isEmpty())
cout << "Stack underflow" << endl;
else
return array[pos].row;
}
int ArrayStack::peekcol(int pos)
{
if (isEmpty())
cout << "Stack underflow" << endl;
else
return array[pos].col;
}
int ArrayStack::count()
{
return (top + 1);
}
void ArrayStack::change(int pos, int value1, int value2)
{
if (isEmpty())
cout << "Stack underflow" << endl;
else
{
array[pos].row = value1;
array[pos].col = value2;
}
}
void ArrayStack::display()
{
for (int i = size - 1; i > -1; i--)
{
cout << array[i].row << " " << array[i].col << endl;
}
}
#endif
问题就在这一行:
Value * array = new Value[size];
这声明了一个新的数组
变量。您正在分配的是数组
,而不是您的成员变量数组
答案很简单,只需将其改为:
array = new Value[size];
谢谢你的快速回复。我终于明白了使用struct动态数组的正确方法。不客气。如果我的答案对你有帮助,请随意投票或接受答案。
array = new Value[size];