FRACTION add(const FRACTION&) const;
第1個const代表不會改變傳入參數
第2個const代表不會改變該物件的data member
class FRACTION {
private:
int num;
int den;
public:
void fraction_init();
FRACTION add(const FRACTION&) const;
FRACTION sub(const FRACTION&) const;
FRACTION mul(const FRACTION&) const;
FRACTION div(const FRACTION&) const;
void printFraction() const;
};
int main()
{
FRACTION f1;
f1.fraction_init();
f1.printFraction();
system("pause");
return 0;
}
void FRACTION::fraction_init() {
num = 0;
den = 1;
}
FRACTION FRACTION::add(const FRACTION& b) const {
FRACTION temp;
temp.den = den * b.den;
temp.num = num * b.den + b.num * den;
return temp;
}
FRACTION FRACTION::sub(const FRACTION& b) const {
FRACTION temp;
temp.den = den * b.den;
temp.num = num * b.den - b.num * den;
return temp;
}
FRACTION FRACTION::mul(const FRACTION& b) const {
FRACTION temp;
temp.den = den * b.den;
temp.num = num * b.num;
return temp;
}
FRACTION FRACTION::div(const FRACTION& b) const {
FRACTION temp;
temp.den = num * b.den;
temp.num = den * b.num;
return temp;
}
void FRACTION::printFraction() const {
cout << num << " / " << den << endl;
}