[RESOLVED] overloading operator+
hi all,
I'm adding two fractions but couldn't figure it out, i tried it for hours. I'm getting 2 errors in it, please tell me how to get it free from bugs.
Code:
#include <iostream>
using namespace std;
class Fractions
{
private:
int num;
int den;
public:
Fractions();
~Fractions();
Fractions(int n,int d);
Fractions(const Fractions& f);
Fractions operator+(const Fractions& f1);
void print();
};
int main()
{
Fractions f(1/3);
Fractions r;
r=f.operator +(1/1);
r.print();
return 0;
}
Fractions::Fractions()
{
num=den=0;
}
Fractions::~Fractions()
{
}
Fractions::Fractions(int n,int d)
{
num=n;
den=d;
}
Fractions::Fractions(const Fractions& f)
{
num=f.num;
den=f.den;
}
Fractions Fractions::operator +(const Fractions& f1)
{
Fractions sum;
int lcm;
int r,s;
lcm=f1.den*this->den;
if(r=lcm/f1.den)
{
r=r*f1.num;
}
if(s=lcm/this->den)
{
s=s*this->num;
}
sum.num=r+s;
sum.den=lcm;
return sum;
}
void Fractions::print()
{
cout<<num/den;
}
Re: overloading operator+
Re: [RESOLVED] overloading operator+
operator + is better written as a nonmember which kicks down to the member operator +=. For a full discussion on why some operators are better written as nonmenbers read this.
Re: [RESOLVED] overloading operator+
Re: [RESOLVED] overloading operator+
Quote:
Originally Posted by
Russco
operator + is better written as a nonmember which kicks down to the member operator +=.
Is += always naturally a member operator?
Say you have an immutable object for example the int object 42. This object itself can never change and suddenly become 43 for example. It stays 42 forever.
This,
n += 1;
is defined to be equivalent to this,
n = n + 1;
for the int class.
Now say n holds the 42 object. In no case is 42 modified to become 43. Instead a new object 43 based on the 42 and 1 objects is returned and assigned to the n variable.
The same applies to all immutable classes in my view. To such classes += just isn't a natural member. An immutable classes cannot have any operator that changes it.
My point is that this idea that one should implement += as a member operator and then + as a non-member operator in terms of += is seriously flawed for immutable classes.
(I'm aware that int technically isn't a class, but conceptually it is and it serves as the preferred model for numerical value classes.)
Re: [RESOLVED] overloading operator+
Quote:
Originally Posted by
nuzzle
...
I'm not sure I understand what you are saying.
You seem to be saying that for classes that don't have operator+=, operator+ shouldn't be implemented in terms of operator+=?
The argument is more of "Once your class has an operator+=, then operator+ can naturally be implemented as a non member in terms of operator+". If your class doesn't have operator+=, then, well... you just write operator+ straight up.