1. 定义一个有理数类Rational,包含分子和分母两个属性,为其重载四则运算和输入输出流,以使用cin和cout对Rational的对象进行输入和输出。根据题目要求写一个C++程序
时间: 2024-11-29 16:35:35 浏览: 0
有理分数的四则算术运算符重载 .cpp
5星 · 资源好评率100%
在C++中,我们可以创建一个名为`Rational`的类来表示有理数,包含`numerator`(分子)和`denominator`(分母)作为私有成员变量,并提供必要的构造函数、赋值操作符以及重载的算术运算符和I/O流操作。以下是实现这个类的一个基本示例:
```cpp
#include <iostream>
#include <sstream>
class Rational {
private:
int numerator;
int denominator;
public:
// 构造函数,初始化有理数
Rational(int num = 0, int den = 1) : numerator(num), denominator(den) {
if (denominator == 0) throw std::invalid_argument("Denominator cannot be zero");
}
// 重载赋值运算符
Rational& operator=(const Rational& other) {
if (this != &other) {
numerator = other.numerator;
denominator = other.denominator;
if (denominator == 0) throw std::invalid_argument("Denominator cannot be zero");
}
return *this;
}
// 重载加法
Rational operator+(const Rational& other) const {
int new_numerator = numerator * other.denominator + other.numerator * denominator;
int new_denominator = denominator * other.denominator;
return Rational(new_numerator, new_denominator);
}
// 其他运算符重载... (这里仅给出加法,其他如减法、乘法和除法类似)
// 用于输入的友元函数
friend std::istream& operator>>(std::istream& is, Rational& rational) {
char sign;
is >> sign >> rational.numerator >> rational.denominator;
if (rational.denominator == 0)
is.setstate(std::ios_base::failbit);
return is;
}
// 输出函数
friend std::ostream& operator<<(std::ostream& os, const Rational& rational) {
if (rational.denominator > 0) {
os << rational.numerator << "/" << rational.denominator;
} else {
os << rational.numerator << " / " << -rational.denominator;
}
return os;
}
};
int main() {
try {
Rational a, b;
std::cout << "Enter the first rational number: ";
std::cin >> a;
std::cout << "Enter the second rational number: ";
std::cin >> b;
Rational sum = a + b;
std::cout << "The sum of " << a << " and " << b << " is: " << sum << std::endl;
} catch (const std::invalid_argument& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
}
```
在这个例子中,我们实现了`Rational`类的基本功能,包括读取输入、计算和显示有理数。注意,为了简化起见,这里只展示了加法和输入输出的部分。实际项目中,你还需要添加其余的算术运算符重载。
阅读全文