C/C++简单的complex类

c++类而大致分为两类,使用指针与不使用指针。使用指针-- string类,不使用指针–complex类

复数类实现复数的加减乘以及数乘,共轭等问题。

//complex0.h(防止与内置的complex库冲突)
#ifndef COMPLEX0_H_
#define COMPLEX0_H_
#include 
using std::istream;
using std::ostream;
class complex0
{
private:
	double m_real;
	double m_imaginary;

public:
	complex0();
	complex0(double real, double imaginary);
	~complex0();

	//类函数声明
	complex0 operator+(const complex0&) const;
	complex0 operator-(const complex0&) const;
	complex0 operator*(const complex0&) const;
	complex0 operator~() const;

	//友元函数声明
	friend complex0 operator*(int x, const complex0&);
	friend bool operator>>(istream & is, complex0&);
	friend ostream& operator<<(ostream & os, const complex0&);
};
#endif
//complex0.cpp
#include "complex0.h"
#include 
using std::istream;
using std::ostream;
using std::cin;
using std::cout;
using std::endl;

//构造函数以及析构函数定义
complex0::complex0()
{
	m_real = m_imaginary = 0;
}
complex0::complex0(double real, double imaginary)
{
	m_real = real;
	m_imaginary = imaginary;
}
complex0::~complex0()
{
}

//成员函数定义
complex0 complex0::operator+(const complex0& a) const
{
	return complex0(m_real + a.m_real, m_imaginary + a.m_imaginary);
}
complex0 complex0::operator-(const complex0& a) const
{
	return complex0(m_real - a.m_real, m_imaginary - a.m_imaginary);
}
complex0 complex0::operator*(const complex0& a) const
{
	return complex0(m_real * a.m_real - m_imaginary * a.m_imaginary, m_real * a.m_imaginary + m_imaginary * a.m_real);
}
complex0 complex0::operator~() const
{
	return complex0(this->m_real, - (this -> m_imaginary));
}

//友元函数定义
complex0 operator*(int x, const complex0& a)
{
	return complex0(x * a.m_real, x * a.m_imaginary);
}
bool operator>>(istream& is, complex0& a)
{
	cout << "real: ";
	while (!(is >> a.m_real))
	{
		is.clear();
		while (cin.get() != '\n')
		{
			continue;
		}
		cout << "real: ";
	}
	cout << endl;
	cout << "imaginary: ";
	while (!(is >> a.m_imaginary))
	{
		is.clear();
		while (cin.get() != '\n')
		{
			continue;
		}
		cout << "imaginary: ";
	}
	cout << endl;
	return 1;
}
ostream& operator<<(ostream& os, const complex0& a)
{
	os << "(" << a.m_real << ", " << a.m_imaginary << "i)" << endl;
	return os;
}
//main.cpp
#include 
using namespace std;
#include "complex0.h"
int main()
{
	complex0 a(3.0, 4.0);
	complex0 c;
	cout << "enter a complex number (q to quit): ";
	while (cin >> c)
	{
		cout << "c is " << c << endl;
		cout << "complex conjugate is " << ~c << endl;
		cout << "a is " << a << endl;
		cout << "a + c is " << a + c << endl;
		cout << "a - c is " << a - c << endl;
		cout << "a * c is " << a * c << endl;
		cout << "2 * c is " << 2 * c << endl;
		cout << "enter a complex number (q to quit): " << endl;
	}
	cout << "done!" << endl;
	system("pause");
	return 0;
}

你可能感兴趣的:(C/C++简单的complex类)