该程序应该通过仅使用一个变量和任意数量的堆栈来检查字符串是否是回文结构。它给了我一些与重载函数有关的错误消息,但我没有看到我重载它的位置。或者我是否宣布堆栈错误?我在他们引用的代码行之后评论了错误消息。谢谢!
int main()
{
stack <char> stackA;
stack <char> stackB;
stack <char> stackC;
char avariable;
cout << "Enter a string: ";
avariable = cin.get();
while(avariable != '\n')
{
if(avariable != ' ')
{
stackA.push(avariable);
stackB.push(avariable);
avariable = cin.get();
}}
stackC.push('$');
while(!stackB.empty())
{
avariable = stackB.top; //error, cannot resolve overloaded function 'top' based on conversion to type 'char'
stackC.push(avariable);
stackB.pop; //statement cannot resolve address of overloaded function
}
avariable = '$';
stackC.push('$');
while(!stackA.empty())
{
if(avariable == stackC.top) //invalid operands of type 'char' and <unresolved overloaded function type>' to binary 'operator=='
{
avariable = stackA.top; //cannot resolve overloaded function 'top' based on conversion to type 'char'
stackA.pop; //cannot resolve address of overloaded function
stackC.pop; //cannot resolve address of overloaded function
}
else
{
cout << "The string of characters entered is not a palindrome." << endl;
}
}
if (stackC.top == '$') //invalid operands of type 'char' and <unresolved overloaded function type>' to binary 'operator=='
{
cout <<"The string of characters entered is a palindrome." << endl;
}
}
答案 0 :(得分:2)
std::stack
模板类只定义了成员函数 top()
和pop()
。您试图将它们作为公共成员对象进行访问。即使没有传递参数,函数调用也需要使用括号。
只需将.top
和.pop
的所有匹配项分别替换为.top()
和.pop()
以及您的计划should at least compile。
另请习惯使用std::
前缀,而不是将整个std
命名空间包含在using namespace std
中。从长远来看,它将为您节省潜在的麻烦。
答案 1 :(得分:1)
要调用函数,需要括号:
stackB.top()
stackB.pop()
由于top
和pop
都没有参数,因此括号为空但仍然是必需的。
这与您完成stackA.empty()
或cin.get()
的位置没有什么不同。