设计一个分数类,将加减乘除运算符重载,加减用成员函数,乘除用友元
时间: 2024-02-25 17:56:53 浏览: 90
下面是一个设计分数类的示例代码,实现了加减乘除的运算符重载:
```cpp
#include <iostream>
#include <cmath>
using namespace std;
class Fraction {
public:
Fraction(int num, int den = 1) : numerator(num), denominator(den) {}
Fraction operator+(const Fraction& rhs);
Fraction operator-(const Fraction& rhs);
friend Fraction operator*(const Fraction& lhs, const Fraction& rhs);
friend Fraction operator/(const Fraction& lhs, const Fraction& rhs);
void print();
private:
int numerator;
int denominator;
void reduce();
};
Fraction Fraction::operator+(const Fraction& rhs) {
int new_num = numerator * rhs.denominator + denominator * rhs.numerator;
int new_den = denominator * rhs.denominator;
return Fraction(new_num, new_den);
}
Fraction Fraction::operator-(const Fraction& rhs) {
int new_num = numerator * rhs.denominator - denominator * rhs.numerator;
int new_den = denominator * rhs.denominator;
return Fraction(new_num, new_den);
}
Fraction operator*(const Fraction& lhs, const Fraction& rhs) {
int new_num = lhs.numerator * rhs.numerator;
int new_den = lhs.denominator * rhs.denominator;
return Fraction(new_num, new_den);
}
Fraction operator/(const Fraction& lhs, const Fraction& rhs) {
int new_num = lhs.numerator * rhs.denominator;
int new_den = lhs.denominator * rhs.numerator;
return Fraction(new_num, new_den);
}
void Fraction::print() {
reduce();
cout << numerator << "/" << denominator << endl;
}
void Fraction::reduce() {
int gcd = abs(__gcd(numerator, denominator));
numerator /= gcd;
denominator /= gcd;
}
int main() {
Fraction a(1, 2);
Fraction b(3, 4);
Fraction c = a + b;
c.print(); // 输出 5/4
c = a - b;
c.print(); // 输出 -1/4
c = a * b;
c.print(); // 输出 3/8
c = a / b;
c.print(); // 输出 2/3
return 0;
}
```
在上面的代码中,我们定义了一个分数类`Fraction`,其中`numerator`表示分子,`denominator`表示分母。构造函数可以接受一个分子和一个分母,如果只传入一个参数,则默认分母为1。`operator+`和`operator-`是成员函数,重载了加法和减法运算符。`operator*`和`operator/`是友元函数,重载了乘法和除法运算符。`print`函数用于输出分数,`reduce`函数用于化简分数。在`main`函数中,我们创建了两个分数`a`和`b`,然后对它们进行加减乘除运算,并输出结果。
阅读全文