函数类/成员函数中的原型

时间:2012-12-07 12:32:36

标签: c++ visual-c++

有人可以向我解释我如何为课程创建函数原型吗?如何将main函数放在代码的开头?

这是我使用class执行常见数学运算的代码。我试着在网上搜索解释,但并没有真正遇到任何问题。任何帮助将不胜感激。

#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;
}

1 个答案:

答案 0 :(得分:1)

假设你的主要使用这个类,你不能把它放在代码的开头,但是你可以在定义成员函数之前把它放在类定义之后。

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