【发布时间】:2018-08-04 10:30:30
【问题描述】:
我有一个项目来比较两个堆栈的内容,但我遇到了这个函数的问题。我相信我已经正确完成了程序的其余部分。我在 B.myCharacters.empty() (表达式必须具有类类型)和 B==B.myCharacters (没有运算符“==”与这些操作数匹配)上遇到错误。
bool CharStack::IsEqual(CharStack & B)
{
if (B.empty())
{
cout << "Stack is empty" << endl;
return false;
}
else if (B.myCharacters.empty())
{
cout << "Stack is empty" << endl;
return false;
}
else if (B == B.myCharacters)
return true;
}
任何帮助将不胜感激。
这是标题和驱动程序。它们是老师为这个项目提供的,我不能更改它们,即使有更好的方法。
#include <iostream>
#include <string>
using namespace std;
const int STACK_CAPACITY = 128;
typedef char StackElement;
class CharStack
{
private:
char myCharacters[STACK_CAPACITY]; // STL stack of chars.
int myTop;
public:
CharStack();
bool empty();
void push(const StackElement & value);
StackElement top() const;
void pop();
void StringToStack(const string & inStr);
friend ostream & operator <<(ostream & out, const CharStack & CS);
CharStack Reverse();
bool IsEqual(CharStack & B);
};
司机
#include <string>
#include <cassert>
#include "Header.h"
using namespace std;
//introduces namespace std
int main(void)
{
ifstream in;
string fileName, line[30];
int i = 0;
CharStack N, M, P;
cout << "Enter file name for palindrome check: ";
cin >> fileName;
in.open(fileName.c_str());
assert(in.is_open());
while (!in.eof())
{
getline(in, line[i]);
N.StringToStack(line[i]);
cout << N << endl;
P = N;
M = N.Reverse();
if (P.IsEqual(M))
cout << "This line is a palindrome line" << endl;
else
cout << "This line is not a palindrome line" << endl;
i++;
}
cout << "\nProgram ended normally.\n";
system("pause");
}
【问题讨论】:
-
请提供minimal reproducible example。在不知道
CharStack是什么的情况下,没有人可以提供帮助。 -
欢迎!不幸的是,除非您发布使用的代码,特别是
CharStack的定义,否则我们无法为您提供太多帮助。请参阅here 了解所需内容。 -
还请注意,说两个空堆栈相等是有道理的。在您的代码 sn-p 中它们不是。
-
您收到有关缺少运算符的错误,因为您尚未定义如何比较两个不同的事物(
B和B.mycharacters)。 IE。你需要定义CharStack::operator==(const T& otherCharacters) const。 (另请注意,您可能不希望在您的实际解决方案中使用此运算符。这只是您当前的解决方案不需要抱怨缺少此运算符的运算符。) -
这次可能不是你的问题,但这个问题中描述的错误迟早会得到你:Why is iostream::eof inside a loop condition considered wrong?