istream未处理的异常,堆栈溢出

时间:2013-04-05 23:58:30

标签: stack-overflow unhandled-exception istream

我对C ++很新,我试图让istream工作。我有一类:

class rat
{
private:
    int num;
    int denom;
public:

    rat();
    rat(const int&, const int&);
    rat(const int&);

    friend ostream& operator << (ostream&, const rat&);
    friend istream& operator >> (istream&, const rat&);
};
rat::rat(void)
{
    num = 0;
    denom = 1;
}

rat::rat(const int &n, const int &d)
{
    num = n;
    denom = d;
    simplify();
}

rat::rat(const int &n)
{
    num = n;
    denom = 1;
}

ostream& operator << (ostream &os, const rat &r1)
{
    os << r1.num;
    os << "/";
    os << r1.denom;
    return os;
}

istream& operator >> (istream &is, const rat &r1)
{
    is >> r1.num;
    is >> r1.denom;
    return is;
}

我也有.cpp:

#include <iostream>
#include <conio.h>
using namespace std;
#include "Rats.h"

void main()
{
    rat r1(3,4), r2(2,3), r3;


    system("cls");
    cout << "Please enter a rational number: ";
    cin >> r3;
}

每当遇到“is&gt;&gt; r1.num”时就会出现问题。线。它给出了错误:RatClass.exe中0x772d15de处的未处理异常:0xC00000FD:堆栈溢出。

同样,我相当新,所以还没有了解可能的原因。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

您可能会接受const rat &r1这一事实,但是通过istream发送您将要更改r1的数据。你不能改变常数。不确定这是否是问题,但这是第一个明显的想法。

试试这个:

istream& operator >> (istream &is, rat &r1)
{
    is >> r1.num;
    is >> r1.denom;
    return is;
}

不要忘记在课堂上更改您的定义:

friend istream& operator >> (istream&, rat&);