Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- class Complex {
- private:
- double real;
- double imaginary;
- public:
- // Конструкторы
- Complex() : real(0.0), imaginary(0.0) {}
- Complex(double r, double i) : real(r), imaginary(i) {}
- // Перегрузка оператора ввода >>
- friend std::istream& operator>>(std::istream& is, Complex& complex) {
- is >> complex.real >> complex.imaginary;
- return is;
- }
- // Перегрузка оператора вывода <<
- friend std::ostream& operator<<(std::ostream& os, const Complex& complex) {
- os << "(" << complex.real << " + " << complex.imaginary << "i)";
- return os;
- }
- // Перегрузка оператора сложения +
- Complex operator+(const Complex& other) const {
- double sumReal = real + other.real;
- double sumImaginary = imaginary + other.imaginary;
- return Complex(sumReal, sumImaginary);
- }
- // Перегрузка оператора вычитания -
- Complex operator-(const Complex& other) const {
- double diffReal = real - other.real;
- double diffImaginary = imaginary - other.imaginary;
- return Complex(diffReal, diffImaginary);
- }
- // Перегрузка оператора неравенства !=
- bool operator!=(const Complex& other) const {
- return real != other.real || imaginary != other.imaginary;
- }
- // Перегрузка оператора равенства ==
- bool operator==(const Complex& other) const {
- return real == other.real && imaginary == other.imaginary;
- }
- };
- int main() {
- Complex c1(2.0, 3.0);
- Complex c2(1.0, 4.0);
- // Ввод комплексных чисел с помощью перегруженного оператора >>
- std::cout << "Enter a complex number (format: real imaginary): ";
- std::cin >> c1;
- std::cout << "Enter another complex number (format: real imaginary): ";
- std::cin >> c2;
- // Вывод комплексных чисел с помощью перегруженного оператора <<
- std::cout << "Complex number 1: " << c1 << std::endl;
- std::cout << "Complex number 2: " << c2 << std::endl;
- // Сложение двух комплексных чисел с помощью перегруженного оператора +
- Complex sum = c1 + c2;
- std::cout << "Sum: " << sum << std::endl;
- // Вычитание двух комплексных чисел с помощью перегруженного оператора -
- Complex diff = c1 - c2;
- std::cout << "Difference: " << diff << std::endl;
- // Проверка на неравенство двух комплексных чисел с помощью перегруженного оператора !=
- if (c1 != c2) {
- std::cout << "The complex numbers are not equal." << std::endl;
- } else {
- std::cout << "The complex numbers are equal." << std::endl;
- }
- // Проверка на равенство двух комплексных чисел с помощью перегруженного оператора ==
- if (c1 == c2) {
- std::cout << "The complex numbers are equal." << std::endl;
- } else {
- std::cout << "The complex numbers are not equal." << std::endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement