【发布时间】:2019-11-17 16:54:13
【问题描述】:
我正在尝试重载
进程以退出代码 -1073741571 (0xC00000FD) 结束
op.h
bool operator<=(const Date& d1, const Date& d2)
{
return d1 <= d2;
}
main.cpp
cout << "Checking <=" << endl;
assert(Date(1,1,2000) <= Date(2,1,2000));
assert(!(Date(2,1,2000) <= Date(1,1,2000)));
assert(Date(2,1,2000) <= Date(1,2,2000));
assert(Date(2,2,2000) <= Date(1,1,2001));
cout << "Checking <= Complete!" << endl;
这里发生了什么?
【问题讨论】:
-
无限递归导致堆栈溢出您的
operator<=(const Date& d1, const Date& d2)在其主体中调用operator<=(const Date& d1, const Date& d2)。 -
您需要将
Date小于/等于另一个的条件实际放入运算符重载中。编译器并不神奇地知道这些是什么,正如其他人所解释的那样,您现在编写它的方式只会导致无限递归。 -
我正在尝试重载 -- 为什么要专门使用那个运算符?在 C++ 中,几乎事实上重载的两个运算符是
==和<。所有其他关系运算符<=、>、>=、!=,都可以派生自==和<。所以我的建议是重载<和==,然后你几乎可以“免费”获得所有其他运算符。 -
更准确地说,如果你有
a < b,那么a >= b就是!(a < b)。编写<的函数,然后>=的函数就是return !(a < b);。同样,a <= b(您正在尝试实现)是return !(b < a);
标签: c++ c++11 operator-overloading