0
我有此任务将所有成员函数转换为朋友函数并添加一个复制构造函数。我本周并没有真正理解给定的演讲。请问任何人都可以在这里将这两个函数中的任何两个函数(addor函数和其他函数之一)进行转换。只是一个功能,我会做剩下的。 Thanx提前从成员函数转换为朋友函数
#include <iostream>
#include <string.h>
using namespace std;
class fraction
{
long num;
long den;
public:
fraction(long,long);
fraction();
~fraction();
void setNum (long);
void setDen (long);
long getNum (void);
long getDen (void);
void print (void);
void add (fraction, fraction);
void sub (fraction, fraction);
void mult (fraction, fraction);
void div (fraction, fraction);
void inc (fraction);
} ; // end of class fraction
long gcd (long x, long y);
fraction::fraction(long l_num, long l_den)
{
num = l_num;
den = l_den;
}
fraction::fraction()
{
}
fraction::~fraction()
{
}
void fraction::setNum (long l_num)
{
num = l_num ;
}
void fraction::setDen (long l_den)
{
den = l_den ;
}
long fraction::getDen ()
{
return den ;
}
long fraction::getNum ()
{
return num ;
}
void fraction:: print (void)
{
cout<<num/gcd(num,den)<<"/"<<den/gcd(num,den) <<endl;
}
void fraction::add (fraction f1, fraction f2)
{
num = (f1.getNum () * f2.getDen ()) + (f1.getDen () * f2.getNum ());
den = (f1.getDen () * f2.getDen ());
}
void fraction::sub (fraction f1, fraction f2)
{
num = (f1.getNum () * f2.getDen ()) - (f1.getDen () * f2.getNum ());
den = (f1.getDen () * f2.getDen ());
}
void fraction::mult (fraction f1, fraction f2)
{
num = (f1.getNum () * f2.getNum ());
den = (f1.getDen () * f2.getDen ());
}
void fraction::div(fraction f1, fraction f2)
{
num = (f1.getNum () * f2.getDen ());
den = (f1.getDen () * f2.getNum ());
}
void fraction::inc (fraction f1)
{
num = (f1.getNum ()) + (f1.getDen ());
den = (f1.getDen ());
}
long gcd (long x, long y)
{
return (x == 0) ? y : gcd (y%x, x);
}
int main ()
{
// define seven instances of the class fraction
fraction f1(1L,2L),f2(3L,4L),f3, f4,f5,f6, f7;
//set values for the numerator and denominator to f1 and print them
//f1.setDen(2L);
//f1.setNum(0L);
f1.print();
//set values for the numerator and denominator to f2 and print them
//f2.setDen(4L);
//f2.setNum(3L);
f2.print();
f3.add(f1, f2);
f3.print();
f4.sub(f1, f2);
f4.print();
f5.mult(f1, f2);
f5.print();
f6.div(f1, f2);
f6.print();
f7.inc(f1);
f7.print();
return 0;
}
我该如何编写getNum()函数? – Yourfavouritenoob 2014-09-22 22:08:47
@ user2951660 long fraction :: getNum()const {return num; } – 2014-09-22 22:15:28
Blagodarya .. Thanx vlad – Yourfavouritenoob 2014-09-22 22:56:22