用类模板实现分数加减乘除的方法
时间: 2024-02-27 10:54:33 浏览: 63
可以使用以下的类模板实现分数加减乘除操作:
```c++
template<typename T>
class Fraction {
public:
Fraction(T numerator = 0, T denominator = 1) : numerator(numerator), denominator(denominator) {}
Fraction<T> operator+(const Fraction<T>& other) const {
T num = numerator * other.denominator + other.numerator * denominator;
T den = denominator * other.denominator;
return Fraction<T>(num, den);
}
Fraction<T> operator-(const Fraction<T>& other) const {
T num = numerator * other.denominator - other.numerator * denominator;
T den = denominator * other.denominator;
return Fraction<T>(num, den);
}
Fraction<T> operator*(const Fraction<T>& other) const {
T num = numerator * other.numerator;
T den = denominator * other.denominator;
return Fraction<T>(num, den);
}
Fraction<T> operator/(const Fraction<T>& other) const {
T num = numerator * other.denominator;
T den = denominator * other.numerator;
return Fraction<T>(num, den);
}
void print() const {
std::cout << numerator << "/" << denominator << std::endl;
}
private:
T numerator;
T denominator;
};
```
这个类模板可以处理整型、浮点型和其他可以进行加减乘除操作的类型。使用时需要指定类型,例如:
```c++
Fraction<int> a(1, 2);
Fraction<int> b(3, 4);
Fraction<int> c = a + b;
c.print(); // 输出 5/4
```
```c++
Fraction<double> a(1.5, 3);
Fraction<double> b(0.5, 2);
Fraction<double> c = a - b;
c.print(); // 输出 0.416667
```
阅读全文