堆栈的重载比较运算符

Overloading comparison operators for stacks

本文关键字:运算符 比较 重载 堆栈      更新时间:2023-10-16

我在这里需要一些帮助:我被要求对 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 的情况。