简体   繁体   English

重载堆栈的比较运算符

[英]Overloading comparison operators for stacks

I need some help here: I'm asked to do some overloading to comparison operators of 2 stacks. 我在这里需要一些帮助:我被要求对2个堆栈的比较运算符进行一些重载。 I have the syntax figured out, I'm just having trouble writing the definition. 我已经弄清楚了语法,我只是在写定义时遇到麻烦。 So please help me. 所以请帮帮我。

At least to one operator overload and then I will do it for the rest. 至少要有一个操作员超载,然后其余部分我都会做。

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);

};

It really depends on what you actually want to compare. 这实际上取决于您实际要比较的内容。 Is it identity of stacks or just number of elements on stacks? 它是堆栈的标识还是堆栈中的元素数量? Since you want to define smaller and greater operators, I assume you want to compare the number of elements in the stacks. 由于您要定义越来越小的运算符,因此我假设您要比较堆栈中元素的数量。

The equal operator would be like this: 等于运算符将是这样的:

bool operator==( const Stack &stack1, const Stack &stack2)
{
  return stack1.list->no == stack2.list->no;
}

Of course you need to consider cases where the list member of a Stack object is NULL. 当然,您需要考虑Stack对象的列表成员为NULL的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM