0

谁能向我解释我如何为类创建函数原型?如何将 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;
}
4

1 回答 1

1

假设您的 main 使用该类,则不能将其放在代码的开头,但可以将其放在类定义之后,成员函数定义之前。

或者您可以将类定义放在头文件中,将成员实现放在单独的源文件中,并将您的 main 函数作为主源文件中的唯一代码。

于 2012-12-07T12:41:27.173 回答