En version der compilerer:
#include <iostream>
using namespace std;
class Rational
{
friend Rational operator+ (int , Rational &);
public:
Rational(int = 0, int = 1);
void red(void);
int getOver(void);
int getNed(void);
void add(Rational, Rational);
void sub(Rational, Rational);
void mul(Rational, Rational);
void div(Rational, Rational);
private:
int over,ned;
};
ostream& operator << (ostream &os, Rational& R)
{
os << R.getOver() << "/" << R.getNed();
return os;
}
Rational::Rational(int o, int n)
{
if (n == 1)
{
n = 0;
}
over = o;
ned = n;
}
int Rational::getNed()
{
return ned;
}
int Rational::getOver()
{
return over;
}
void Rational::red()
{
int taeller;
for (taeller = 2; taeller <= over; taeller++)
{
while (over % taeller == 0 && ned % taeller == 0)
{
over = over / taeller;
ned = ned / taeller;
}
}
}
void Rational::add(Rational brok1, Rational brok2)
{
ned = (brok1.getNed() * brok2.getNed());
over = (brok1.getOver() * brok2.getNed()) + (brok2.getOver()* brok1.getNed());
red();
}
void Rational::sub(Rational brok1, Rational brok2)
{
ned = (brok1.getNed() * brok2.getNed());
over = (brok1.getOver() * brok2.getNed()) - (brok2.getOver()* brok1.getNed());
red();
}
void Rational::mul(Rational brok1, Rational brok2)
{
ned = brok1.getNed() * brok2.getNed();
over = brok1.getOver() * brok2.getOver();
red();
}
void Rational::div(Rational brok1, Rational brok2)
{
ned = (brok1.getNed() * brok2.getOver());
over = (brok1.getOver() * brok2.getNed());
red();
}
//nyt
Rational operator+(int left, Rational &right)
{
Rational tmp;
tmp.over = (left * right.ned) + right.over;
tmp.ned = right.ned;
tmp.red();
return tmp;
}
int main(void)
{
int o1,n1,o2,n2;
cout << "Indtast forste broks taellerens : ";
cin >> o1;
cout << "Indtast forste Naevrens vaerdi : ";
cin >> n1;
cout << "Indtast forste broks taellerens : ";
cin >> o2;
cout << "Indtast forste Naevrens vaerdi : ";
cin >> n2;
Rational brok1(o1,n1);
Rational brok2(o2,n2);
Rational brok3;
brok1.red();
cout << "brok1 = "<< brok1.getOver() << "/" << brok1.getNed() <<endl;
brok2.red();
cout << "brok2 = "<< brok2.getOver() << "/" << brok2.getNed() <<endl;
brok3.add(brok1,brok2);
cout << "ADD = "<< brok3.getOver() << "/" << brok3.getNed() <<endl;
brok3.sub(brok1,brok2);
cout << "SUB = "<< brok3.getOver() << "/" << brok3.getNed() <<endl;
brok3.mul(brok1,brok2);
cout << "Mul = "<< brok3.getOver() << "/" << brok3.getNed() <<endl;
brok3.div(brok1,brok2);
cout << "Mul = "<< brok3.getOver() << "/" << brok3.getNed() <<endl;
// nyt
Rational R = 2 + brok1;
cout << endl << "brok1+2 = " << R << endl;
}
Jeg har puttet det hele i én fil.
Ændret + operatoren og tilføjet en << operator for Rational.
Og lavet en variabel til at holde "2 + brok1" da den ikke vil streame det direkte.
I øvrigt var det nok bedre at lave en constructor til Rational der taget en int.
Jeg gidder normalt ikke at svare spørgsmål der er stillet i mere end et forum samtidig.