定义一个分数类,其数据成员为分子和分母,用成员函数重载=、+、-,用友元函数重载*、/,最终得到最简分数
时间: 2024-01-22 10:21:20 浏览: 94
以下是一个基本的分数类实现:
```c++
#include <iostream>
class Fraction {
public:
Fraction(int numerator = 0, int denominator = 1) : numerator(numerator), denominator(denominator) {}
// 重载赋值运算符
Fraction& operator=(const Fraction& other) {
numerator = other.numerator;
denominator = other.denominator;
return *this;
}
// 重载加法运算符
Fraction operator+(const Fraction& other) const {
int newNumerator = numerator * other.denominator + other.numerator * denominator;
int newDenominator = denominator * other.denominator;
return simplify(newNumerator, newDenominator);
}
// 重载减法运算符
Fraction operator-(const Fraction& other) const {
int newNumerator = numerator * other.denominator - other.numerator * denominator;
int newDenominator = denominator * other.denominator;
return simplify(newNumerator, newDenominator);
}
// 友元函数,重载乘法运算符
friend Fraction operator*(const Fraction& lhs, const Fraction& rhs) {
int newNumerator = lhs.numerator * rhs.numerator;
int newDenominator = lhs.denominator * rhs.denominator;
return simplify(newNumerator, newDenominator);
}
// 友元函数,重载除法运算符
friend Fraction operator/(const Fraction& lhs, const Fraction& rhs) {
int newNumerator = lhs.numerator * rhs.denominator;
int newDenominator = lhs.denominator * rhs.numerator;
return simplify(newNumerator, newDenominator);
}
// 输出分数
void print() const {
std::cout << numerator << "/" << denominator << std::endl;
}
private:
// 分子
int numerator;
// 分母
int denominator;
// 辗转相除法求最大公约数
int gcd(int a, int b) const {
return b == 0 ? a : gcd(b, a % b);
}
// 约分
Fraction simplify(int num, int den) const {
int g = gcd(num, den);
return Fraction(num / g, den / g);
}
};
int main() {
Fraction f1(3, 4);
Fraction f2(1, 2);
Fraction f3 = f1 + f2;
f3.print();
Fraction f4 = f1 - f2;
f4.print();
Fraction f5 = f1 * f2;
f5.print();
Fraction f6 = f1 / f2;
f6.print();
return 0;
}
```
输出:
```
5/4
1/4
3/8
3/2
```
阅读全文