我在这里需要一些帮助:我被要求对 2 个堆栈的比较运算符进行一些重载。我弄清楚了语法,只是在编写定义时遇到了问题。所以请帮助我。
至少一个运算符过载,然后我会为其余的做。
struct linklist
{
int no;
struct linklist *next;
};
class Stack
{
private:
linklist *list,*head;
public://constructor and destructor
Stack();
~Stack();
public:// main functions
void push();
void show();
void pop();
public://overloaded operations
friend bool operator == (const Stack &stack1, const Stack &stack2);
friend bool operator != (const Stack &stack1, const Stack &stack2);
friend bool operator < (const Stack &stack1, const Stack &stack2);
friend bool operator > (const Stack &stack1, const Stack &stack2);
};
最佳答案
这实际上取决于您实际想要比较的内容。是堆栈的身份还是堆栈上元素的数量?由于您想定义更小和更大的运算符,我假设您想要比较堆栈中元素的数量。
等于运算符是这样的:
bool operator==( const Stack &stack1, const Stack &stack2)
{
return stack1.list->no == stack2.list->no;
}
当然需要考虑 Stack 对象的列表成员为 NULL 的情况。
关于c++ - 为堆栈重载比较运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19575623/