[英]Unhandled exception when overloading << operator
I am trying to overload the << operator for a New Integer class that detects overflow of operations and below are my parts of codes: 我正在尝试为新的Integer类重载<<操作符,以检测操作的溢出,下面是我的代码部分:
class NewInteger{
private:
int num;
public:
NewInteger();
NewInteger(int);
friend std::ostream &operator <<(std::ostream& out, const NewInteger& rhs);
NewInteger operator+ (NewInteger);
.../ many other member functions/
}
Implementations are: 实现为:
NewInteger NewInteger::operator+(NewInteger n)
{
int a = this->getValue();
int b = n.getValue();
if (a > 0 && b > max - a) {
throw std::exception();
std::cout << "studpid" << std::endl;
}
if (a < 0 && b < min - a) {
throw std::exception();
}
return NewInteger(a + b);
}
std::ostream & operator<<(std::ostream & out, const NewInteger& rhs)
{
out << rhs;
return out;
}
In the main.cpp, I try to test the code by running: 在main.cpp中,我尝试通过运行以下代码来测试代码:
NewInteger n7(4);
NewInteger n8(5);
std::cout << n7.operator+(n8) << std::endl;
The code builds fine and when I run it on Visual Studio 2015, it causes the program to close without giving a fatal error. 该代码构建良好,当我在Visual Studio 2015上运行它时,它会导致程序关闭而不会出现致命错误。 So when I debug the code, it gives me: `
因此,当我调试代码时,它给了我:
Exception thrown at 0x00C43B49 in NewInteger.exe: 0xC00000FD: Stack overflow (parameters: 0x00000001, 0x00192F90)
and the break point appears right at the implementation of operator<<. 断点恰好出现在operator <<的实现上。 But I cannot figure out what exception I should try to catch at the implementation.
但是我无法弄清楚应该在实现过程中捕获什么异常。
Can somebody please tell me what is the cause of this? 有人可以告诉我这是什么原因吗?
std::ostream & operator<<(std::ostream & out, const NewInteger& rhs)
{
out << rhs;
return out;
}
The first line calls operator<<
on out
and rhs
-- which is the function you're defining. 第一行调用
operator<<
on out
和rhs
这是您要定义的函数。 You have infinite recursion. 您具有无限递归。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.