运算符重载建立分数类,1.数据成员包括:分子和分母,操作包括:两个分数的加法、乘法、比较大小和输出。拓展:添加实现约分的函数通过成员函数运算符重载实现
时间: 2024-05-24 15:11:56 浏览: 201
分数-运算符重载
#include <iostream>
using namespace std;
class Fraction{
private:
int numerator; // 分子
int denominator; // 分母
public:
Fraction(int num = 0, int den = 1): numerator(num), denominator(den){}
Fraction(const Fraction& f): numerator(f.numerator), denominator(f.denominator){}
~Fraction(){}
int gcd(int a, int b); // 辗转相除法求最大公约数
void reduce(); // 约分
Fraction operator+(const Fraction& f); // 加法运算符重载
Fraction operator*(const Fraction& f); // 乘法运算符重载
bool operator>(const Fraction& f); // 大小比较运算符重载
friend ostream& operator<<(ostream& os, const Fraction& f); // 输出运算符重载
};
int Fraction::gcd(int a, int b){
if(b == 0) return a;
else return gcd(b, a % b);
}
void Fraction::reduce(){
int g = gcd(numerator, denominator);
numerator /= g;
denominator /= g;
}
Fraction Fraction::operator+(const Fraction& f){
Fraction sum;
sum.numerator = numerator * f.denominator + denominator * f.numerator;
sum.denominator = denominator * f.denominator;
sum.reduce();
return sum;
}
Fraction Fraction::operator*(const Fraction& f){
Fraction product;
product.numerator = numerator * f.numerator;
product.denominator = denominator * f.denominator;
product.reduce();
return product;
}
bool Fraction::operator>(const Fraction& f){
int n1 = numerator * f.denominator;
int n2 = f.numerator * denominator;
return n1 > n2;
}
ostream& operator<<(ostream& os, const Fraction& f){
os << f.numerator << "/" << f.denominator;
return os;
}
int main(){
Fraction f1(3, 5);
Fraction f2(1, 2);
Fraction sum = f1 + f2;
Fraction product = f1 * f2;
bool compare = f1 > f2;
cout << "f1 = " << f1 << endl;
cout << "f2 = " << f2 << endl;
cout << "f1 + f2 = " << sum << endl;
cout << "f1 * f2 = " << product << endl;
if(compare) cout << "f1 > f2" << endl;
else cout << "f1 <= f2" << endl;
return 0;
}
阅读全文