11---7

//Complex.h
#ifndef COMPLEX_H
#define COMPLEX_H

#include<iostream>

class Complex
{
private:
	double x;
	double y;

public:
	Complex();
	Complex(double a, double b = 0.0);

	Complex operator+(const Complex& c)const;
	Complex operator-(const Complex& c)const;
	Complex operator*(const Complex& c)const;
	Complex operator*(double n) const;
	Complex operator~();

	friend Complex operator*(double n, const Complex& c);
	friend std::istream& operator>>(std::istream& is, Complex& c);
	friend std::ostream& operator<<(std::ostream& os, const Complex& c);
};

#endif // !COMPLEX_H
//Complex.cpp
#include "Complex.h"

//constructor
Complex::Complex()
{
	x = 0.0;
	y = 0.0;
}

Complex::Complex(double a, double b)
{
	x = a;
	y = b;
}

//operator overloading
Complex Complex::operator+(const Complex& c) const
{
	Complex sum;
	sum.x = x + c.x;
	sum.y = y + c.y;
	return sum;
}

Complex Complex::operator-(const Complex& c) const
{
	Complex diff;
	diff.x = x - c.x;
	diff.y = y - c.y;
	return diff;
}

Complex Complex::operator*(const Complex& c) const
{
	Complex mult;
	mult.x = x * c.x - y * c.y;
	mult.y = x * c.y + y * c.x;
	return mult;
}

Complex Complex::operator*(double n) const
{
	Complex mult;
	mult.x = x * n;
	mult.y = y * n;
	return mult;
}

Complex Complex::operator~()
{
	return Complex(x, -y);
}

//friend method:
Complex operator*(double n, const Complex& c)
{
	return c * n;
}

std::istream& operator>>(std::istream& is, Complex& c)
{
	std::cout << "real: ";
	is >> c.x;
	std::cout << "imaginary: ";
	is >> c.y;
	return is;
}

std::ostream& operator<<(std::ostream& os, const Complex& c)
{
	os << "(" << c.x << "," << c.y << "i)\n";
	return os;
}

 

//usecomp.cpp
#include<iostream>
#include"Complex.h"

using namespace std;

int main()
{
	Complex a(3.0, 4.0);
	Complex c;

	cout << "Enter a complex number (q to quit):\n";
	while (cin >> c)
	{
		cout << "c is " << c << "\n";
		cout << "complex conjugate is " << ~c << "\n";
		cout << "a is " << a << "\n";
		cout << "a + c is " << a + c << "\n";
		cout << "a - c is " << a - c << "\n";
		cout << "a * c is " << a * c << "\n";
		cout << "2 * c is " << 2 * c << "\n";
		cout << "Enter a complex number (q to quit):\n";
	}
	cout << "Done!\n";

	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值