我正在为我的作业制作括号匹配程序,我不太确定如何准确地解决这个问题。我在调用我的堆栈函数时遇到错误,说必须使用is_balanced函数中的相对特定对象来创建非静态成员引用。为什么会发生此错误以及如何解决?谢谢你的帮助。
#include <iostream>
#include <string>
#include "StringStack.h"
using namespace std;
char parentest[];
int main() {
//variables
string paren;
StringStack *stack;
//user input
cout << "Please enter a string of parentheses";
cin >> paren;
//turn string into char array
char parentest[paren.length] = paren;
//set size of the stack equal to the length of the char array.
stack->stackSize = parentest.length;
//display the string of balanced parantheses
cout << is_balanced(parentest);
system("Pause");
return 0;
}
//balances the parentheses and returns the string
bool is_balanced(string s) {
bool status;
for (int i = 0; i < s.length, i++) {
cout << s[i] << endl;
StringStack::push(s[i]);
}
StringStack::isEmpty();
if (StringStack::isEmpty) {
status = true;
}
return status;
}
//constructor creates an empty stack
StringStack::StringStack(int size)
{
stackArray = new string[size];
stackSize = size;
top = -1;
}
//copy constructor
StringStack::StringStack(const StringStack &obj) {
//creates stack array
if (obj.stackSize > 0) {
stackArray = new string[obj.stackSize];
}
else {
stackArray = nullptr;
}
//copies stack contents
stackSize = obj.stackSize;
for (int count = 0; count < stackSize; count++) {
stackArray[count] = obj.stackArray[count];
}
//set top of stack
top = obj.top;
}
//Destructor
StringStack::~StringStack() {
delete[] stackArray;
}
//puts a value at top of the stack
void StringStack::push(string p) {
if (isFull()) {
cout << "The stack is full. \n";
}
else {
top++;
stackArray[top] = p;
}
}
void StringStack::pop() {
if (isEmpty()) {
cout << "the stack is empty";
}
else {
top--;
return top;
}
}
bool StringStack::isFull() const {
bool status;
if (top == stackSize - 1) {
status = true;
}
else {
status = false;
}
return status;
}
bool StringStack::isEmpty() const {
bool status;
if (top == -1) {
status = true;
}
else {
status = false;
}
return status;
}
答案 0 :(得分:0)
因为您正在调用非静态成员函数,就好像它们是静态的一样。尽管你有一个StringStack指针,你也永远不会分配一个StringStack实例。当您取消引用stack->stackSize = parentest.length;
处的指针时,您将发生分段错误。
这个char parentest[paren.length] = paren;
也是错误的。
您所展示的代码几乎没有任何正确之处。
这是一个如何实例化类以及如何调用成员函数的示例:
StringStack stack(100);
string s( "a string" );
stack.push( s );