Question

I'm fairly new to C++, and am trying to get the istream to work. I have a class of:

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

I also have a .cpp of:

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

My problem occurs whenever it comes across the "is >> r1.num;" line. It gives me the error: Unhandled exception at 0x772d15de in RatClass.exe: 0xC00000FD: Stack overflow.

Again, I'm fairly new, so have not learned what the possible cause could be yet. Any help is appreciated.

Était-ce utile?

La solution

Looks like it might be the fact that you're accepting const rat &r1 but by sending data from the istream you would be changing r1. You can't change constants. Not sure if this is the issue but that's the first obvious thing that came to mind.

Try this:

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

Don't forget to change your definition in the class:

friend istream& operator >> (istream&, rat&);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top