c++ - 为堆栈重载比较运算符

标签 c++ stack operator-overloading friend-function

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

相关文章:

c++ - 如何更改文本字段的大小?

c++ - 在特定视口(viewport)中绘制相机位置

c++ - 如何调试 'value of ESP was not saved across function call'错误?

带堆栈和链表的 C 语言计算器

windows - 堆栈增长在 Windows 和 Linux 上如何工作?

指针的 C++ 运算符重载

c++ - 一个重载的函数调用运算符可以有多少个操作数?

c++ - Cmake 和 QT5 - Include 只接受一个参数

python - xtensor 将 numpy 数组传递给具有 xt::xtensor 参数类型的函数

c++ - C++中运算符重载中的参数数量