所以,在类里面,我们学习了数组抽象数据结构的实现,并使用我们制作的数组类,我们将堆栈抽象数据结构实现为一个类。
#include <iostream>
#ifndef ARRAYADT1_H
#define ARRAYADT1_H
using namespace std;
class ArrayADT1
{
public:
ArrayADT1();
ArrayADT1(int);
virtual ~ArrayADT1();
bool setElement(int, int);
int getElement(int);
int getCapacity();
protected:
private:
int capacity;
int* elements;
};
#endif // ARRAYADT1_H
ArrayADT1::ArrayADT1(){
capacity=0;
elements=NULL;
}
ArrayADT1::ArrayADT1(int arraySize){
capacity=arraySize;
elements=new int[arraySize];
}
bool ArrayADT1::setElement(int index, int value){
elements[index]=value;
return(true);
}
int ArrayADT1::getElement(int index){
return(elements[index]);
}
int ArrayADT1::getCapacity(){
return(capacity);
}
ArrayADT1::~ArrayADT1(){
delete[] elements;
}
#ifndef STACKADT1_H
#define STACKADT1_H
using namespace std;
class StackADT1
{
public:
StackADT1()=delete; //disable creation of stack without specifying capacity
StackADT1(int); //create stack of capacity
bool push(int);
int pop();
bool isFull();
bool isEmpty();
int length();
virtual ~StackADT1();
protected:
private:
int ValueCount;
ArrayADT1 members;
};
#endif // STACKADT1_H
#include <iostream>
StackADT1::StackADT1(int stackCapacity): members(stackCapacity){
ValueCount=0;
}
int StackADT1::length(){
return(ValueCount);
}
bool StackADT1::isEmpty(){
if(ValueCount==0)
return(true);
return(false);
}
bool StackADT1::isFull(){
if(ValueCount==members.getCapacity())
return(true);
return(false);
}
int StackADT1::pop(){
if(isEmpty()){
cout<<"The Stack is empty"<<"\n";
return(-1);
}
ValueCount--;
return(members.getElement(ValueCount));
}
bool StackADT1::push(int value){
if(isFull()){
cout<<"The stack is full"<<"\n";
return(false);
}
members.setElement(ValueCount, value);
ValueCount++;
return(true);
}
StackADT1::~StackADT1(){
//I would like to know what happens here
//dtor
}
我想知道这两种情况下的析构函数。在ArrayADT1类中,我们显式地使用了delete方法,但在StackADT1类中我们没有这样做。之后堆栈是否也会被销毁
return 0;
叫什么?
最佳答案
In the ArrayADT1 class, we explicitly used the delete method, but we do no such thing in the StackADT1 class
您还在 ArrayADT1 类中显式使用了 new 表达式,但没有在 StackADT1 中使用 new 表达式。这是可以预料的,因为我们只删除新的内容。
//I would like to know what happens here //dtor
该析构函数的主体中没有任何反应,因为主体是空的。析构函数将销毁(空)主体之后的子对象。
ArrayADT1
是可复制的,但复制它会导致未定义的行为。这不好。要解决这个问题,请遵循五法则。我还建议学习 RAII 习惯用法。该示例程序似乎是实现 RAII 的一个有缺陷的尝试。
接下来,我建议学习 std::unique_ptr
这是管理内存的更好方法。
关于c++ - 想要销毁我制作的堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69073522/