| xarrtarrant (11) | |||
|
So I am making a rational number class. Ive got it most of the way done accept when I use the + operator the program crashes. So I have a Rational class. All my operators are in the Rational class. My << and >> are friends of Rational class.
When I declare Rational objects a, b , c and try say a=b+c the program stops working. Is this operator wrong or could it be a problem with the = operator? I just don't know. Any help would be awesome. Thanks I can post more of the code if needed. | |||
|
|
|||
| Peter87 (3911) | |
| operator+ looks correct. Can you show the definition of Rational? | |
|
Last edited on
|
|
| xarrtarrant (11) | |||
Yes sir. Here it.
| |||
|
|
|||
| Peter87 (3911) | |
Make sure you have implemented the copy constructor Rational(const Rational &); and the copy assignment operator Rational &operator=(const Rational &); correctly.You should probably also have a destructor, but I don't think that is the cause of the problem. http://en.wikipedia.org/wiki/Rule_of_three_%28C%2B%2B_programming%29 | |
|
|
|
| xarrtarrant (11) | |||||
Ok. So I think the assignment operator is working...
I think it might be a problem with the copy constructor then.
See any problems besides that memory leak? | |||||
|
Last edited on
|
|||||
| ne555 (4383) | |
|
Besides leaking memory, that constructor does nothing. Edit: it may be dereferencing an invalid pointer too. ¿what are your `a' and `p' members for? > try say a=b+c the program stops working. debugger, backtrace By the way, Rational operator+(const Rational &) const;
| |
|
Last edited on
|
|
| Chervil (1205) | |||
Shouldn't line 4 read as follows: temp.num = (num*rhs.denom)+(rhs.num*denom);
| |||
|
|
|||
| xarrtarrant (11) | |
|
That is supposed to be a constructor to copy another object... implemented as Rational a; Rational e(a); p is for the copy constructor. a is just for the string conversions. And thanks. Yeah that is supposed to a *. | |
|
Last edited on
|
|
| ne555 (4383) | |||
|
Limit the scope of your variables. I don't understand how are you planning to use `p', but it looks that `a' is just an auxiliar. In the copy constructor that you posted, you are setting a local variable. Your member `p' remains uninitialized (as well as `num' and `denom')
| |||
|
|
|||
| xarrtarrant (11) | |
| Ok I read over the copy constructor material... Just not getting it. | |
|
|
|