我的第一个问题在这里。请原谅,我刚刚进入C++并开始使用DS。堆!!!
我的代码:我认为
using namespace std;
typedef char stackElement;
class Stack
{
public:
stackElement *contents; //dynamically allocated: as we do not know what would be the size of our array.
int top, maxSize; // current Top index in the array
//max size of the array; we need it to know if the array is full
Stack(int maxSize)
{
contents = new stackElement(maxSize);
this.maxSize = maxSize;
if(contents == NULL)
{
cout<<"Insufficient memory";
exit(1);
}
top = -1;
}
~Stack()
{
delete [] contents;
contents = NULL;
maxSize = 0;
top = -1;
}
bool isEmpty()const
{
return top < 0;
}
bool isFull() const
{
return top == maxSize - 1;
}
void push(stackElement element)
{
if(isFull())
{
cout<<"STACK IS ALREADY FULL";
exit(1);
}
top = top + 1;
contents[top] = element;
}
};
int main()
{
cout<<"STACK IMPLEMENTATION";
int i = 1;
Stack s1(i);
s1.push('a');
s1.push('1');
return 0;
}
我收到此错误:
error: request for member 'maxSize' in 'this', which is of non-class type 'Stack* const'
如果有的话,你必须写this->maxSize = maxSize;
, since this
is a pointer.
但最好不要这样写,而是使用构造函数初始化列表:
explicit Stack(int m)
: contents(new stackElement[m]), top(-1), maxSize(m)
{
// nothing else to do
}
我还添加了explicit
这样你就不会意外转换5
into a Stack
.
你还把数组初始化写错了。
另外,你不需要检查contents
不为空:当new
失败,它退出并出现异常,确实如此not返回一个空指针。 (当你从对象的角度思考时,这种行为是没有意义的。)
重要的是要注意你最多有one naked new
- 构造函数中的表达式。其他任何情况都是异常安全灾难,并且表明您需要重构和使用单一职责资源管理类。
析构函数应该是:~Stack() { delete [] contents; }
其他一切都是毫无意义的浪费。
想象一下你必须pay对于您编写的每一行代码。要有耐心,失去源头,思考。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)