运算符重载时未处理<<异常

Unhandled exception when overloading << operator

本文关键字:lt 异常 未处理 重载 运算符      更新时间:2023-10-16

我试图超载&lt;&lt;一个新的整数类的操作员检测操作溢出及以下是我的代码部分:

    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/
            }

实现是:

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

在main.cpp中,我尝试通过运行来测试代码:

    NewInteger n7(4);
    NewInteger n8(5);
    std::cout << n7.operator+(n8) << std::endl;

代码构建正常,当我在Visual Studio 2015上运行它时,它会导致该程序关闭而不会出现致命错误。因此,当我调试代码时,它给了我:`

Exception thrown at 0x00C43B49 in NewInteger.exe: 0xC00000FD: Stack overflow (parameters: 0x00000001, 0x00192F90)

,断裂点出现在实施操作员&lt;&lt;中。但是我无法弄清楚我应该尝试在实施中捕获哪些例外。

有人可以告诉我这是什么原因吗?

std::ostream & operator<<(std::ostream & out, const NewInteger& rhs)
{
    out << rhs;
    return out;
}

第一行调用outrhs上的operator<< - 这是您定义的功能。您有无限的递归。