Can anyone explain to me how I create function prototypes for class? How do I put the main function at the beginning of my code?
here is my code for performing common mathematical operations using class. I tried searching the web for explanations, but did not really come across any. Any help would be appreciated.
#include <iostream>
using namespace std;
class fraction
{
public:
fraction();
fraction(int, int);
friend fraction operator + (fraction f1, fraction f2);
friend fraction operator - (fraction f1, fraction f2);
friend fraction operator * (fraction f1, fraction f2);
friend fraction operator / (fraction f1, fraction f2);
void readFrac();
void displayFrac();
private:
int num;
int denom;
};
fraction::fraction()
{
num = 0;
denom = 1;
}
fraction::fraction(int n, int d)
{
num = n;
denom = d;
}
void fraction::readFrac()
{
char slash;
do {
cout << "Please enter numerator / denominator: " << endl;
cin >> num >> slash >> denom;
} while (slash != '/');
}
void fraction::displayFrac()
{
cout << num << '/' << denom;
}
fraction operator + (fraction f1, fraction f2)
{
fraction temp(f1.num*f2.denom + f1.denom*f2.num, f1.denom*f2.denom);
return temp;
}
fraction operator - (fraction f1, fraction f2)
{
fraction temp(f1.num*f2.denom - f1.denom*f2.num, f1.denom*f2.denom);
return temp;
}
fraction operator * (fraction f1, fraction f2)
{
fraction temp(f1.num*f2.num, f1.denom*f2.denom);
return temp;
}
fraction operator / (fraction f1, fraction f2)
{
fraction temp(f1.num*f2.denom, f1.denom*f2.num);
return temp;
}
int main()
{
fraction f1, f2, f3;
cout << "Please enter first fraction: " << endl;
f1.readFrac();
cout << "Please enter second fraction: " << endl;
f2.readFrac();
f3 = f1 + f2; cout << endl << endl;
f1.displayFrac(); cout << " + ";
f2.displayFrac(); cout << " = ";
f3.displayFrac(); cout << endl << endl;
f3 = f1 - f2; cout << endl << endl;
f1.displayFrac(); cout << " - ";
f2.displayFrac(); cout << " = ";
f3.displayFrac(); cout << endl << endl;
f3 = f1 * f2; cout << endl << endl;
f1.displayFrac(); cout << " * ";
f2.displayFrac(); cout << " = ";
f3.displayFrac(); cout << endl << endl;
f3 = f1 / f2; cout << endl << endl;
f1.displayFrac(); cout << " / ";
f2.displayFrac(); cout << " = ";
f3.displayFrac(); cout << endl << endl;
}
Assuming your main uses the class, you cannot put it at the beginning of your code, but you can put it right after the class definition, before the definition of the member functions.
Or you could just put the class definition in a header, the member implementations in a separate source file, and have your main function as the only bit of code in the main source file.