【发布时间】:2013-10-24 20:08:14
【问题描述】:
我需要一些帮助:我被要求对 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);
};
【问题讨论】:
-
关于运算符重载你想知道的一切都是here
-
" 我只是在编写定义时遇到了麻烦" 你试过什么?什么地方出了错?你能告诉我们错误信息吗?
-
是的,我试过这样,返回 stack1 == stack2
-
@Nicholas 这会创建一个无限循环(或无限递归),对吧?您需要通过以正确的方式比较类的成员来实现它。一旦你成功实现了
==,当你想实现!=,记住a!=b应该和!(a==b)一样。祝你好运! -
一个重载的操作符可以返回任何东西。你可以只写
friend bool operator == (const Stack &stack1, const Stack &stack2) { return true; },但这不会很有用。例如,如果运算符返回 true 当且仅当两个堆栈具有相同数量的元素,并且堆栈 1 的元素编号 #i 等于堆栈 2 的元素 #i(对于从 0 到元素总数)。
标签: c++ stack operator-overloading friend-function