谁能向我解释我如何为类创建函数原型?如何将 main 函数放在代码的开头?
这是我使用类执行常见数学运算的代码。我尝试在网上搜索解释,但并没有真正遇到任何解释。任何帮助,将不胜感激。
#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;
}