设计一个类,用自己的成员函数重载运算符,使对整型的运算符=、+、-、*、/ 适用于分数运算。要求: (1)输出结果是最简分数(可以是带分数); (2)分母为1,只输出分子。 (3)用友元函数重载运算符,使对整型的运算符=、+、-、*、/ 适用于分数运算。
时间: 2023-07-10 07:04:11 浏览: 84
以下是一个实现上述要求的分数类Fraction:
```cpp
#include <iostream>
using namespace std;
int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
class Fraction {
public:
Fraction(int num = 0, int den = 1) {
int d = gcd(num, den);
numerator = num / d;
denominator = den / d;
if (denominator < 0) {
numerator = -numerator;
denominator = -denominator;
}
}
Fraction& operator=(int num) {
numerator = num;
denominator = 1;
return *this;
}
Fraction operator+(const Fraction& other) const {
int num = numerator * other.denominator + other.numerator * denominator;
int den = denominator * other.denominator;
return Fraction(num, den);
}
Fraction operator-(const Fraction& other) const {
int num = numerator * other.denominator - other.numerator * denominator;
int den = denominator * other.denominator;
return Fraction(num, den);
}
Fraction operator*(const Fraction& other) const {
int num = numerator * other.numerator;
int den = denominator * other.denominator;
return Fraction(num, den);
}
Fraction operator/(const Fraction& other) const {
int num = numerator * other.denominator;
int den = denominator * other.numerator;
return Fraction(num, den);
}
friend Fraction operator+(int num, const Fraction& frac) {
return Fraction(num) + frac;
}
friend Fraction operator-(int num, const Fraction& frac) {
return Fraction(num) - frac;
}
friend Fraction operator*(int num, const Fraction& frac) {
return Fraction(num) * frac;
}
friend Fraction operator/(int num, const Fraction& frac) {
return Fraction(num) / frac;
}
friend ostream& operator<<(ostream& os, const Fraction& frac) {
if (frac.denominator == 1) {
os << frac.numerator;
} else if (abs(frac.numerator) >= frac.denominator) {
int integer = frac.numerator / frac.denominator;
int num = abs(frac.numerator) % frac.denominator;
if (num == 0) {
os << integer;
} else {
os << integer << " " << num << "/" << frac.denominator;
}
} else {
os << frac.numerator << "/" << frac.denominator;
}
return os;
}
private:
int numerator;
int denominator;
};
```
这个类重载了运算符=、+、-、*、/,并且定义了友元函数来支持整数和分数之间的运算。在输出时,它会将分数转换为最简分数或带分数的形式。
下面是一个例子,展示了如何使用Fraction类:
```cpp
int main() {
Fraction a(1, 2);
Fraction b(3, 4);
Fraction c = a + b;
cout << c << endl; // 输出 5/4
c = a - b;
cout << c << endl; // 输出 -1/4
c = a * b;
cout << c << endl; // 输出 3/8
c = a / b;
cout << c << endl; // 输出 2/3
Fraction d = 2 + a;
cout << d << endl; // 输出 5/2
d = 2 - a;
cout << d << endl; // 输出 3/2
d = 2 * a;
cout << d << endl; // 输出 1
d = 2 / a;
cout << d << endl; // 输出 4
return 0;
}
```
阅读全文