c++学习笔记--由复数类看运算符重载

c++学习笔记--由复数类看运算符重载_第1张图片

c++学习笔记--由复数类看运算符重载_第2张图片

#include
#include

using namespace std;

class Complex;//前置声明 在一个需要声明未定义完成的类,比如 Complex 还未定义 之前要声明有这个类

/*Complex operator+(const Complex& c2,const Complex& c1);
Complex operator+(const int a,const Complex& c1);
*/
ostream operator<<(ostream& out,const Complex& c);//重定向的重载 返回值是一个ostream类的一个对象 这样可以连续输出cout<

3.28 更新:

#include
#include

using namespace std;

class Complex;//前置声明 在一个需要声明未定义完成的类,比如 Complex 还未定义 之前要声明有这个类

/*Complex operator+(const Complex& c2,const Complex& c1);
Complex operator+(const int a,const Complex& c1);
*/
ostream operator<<(ostream& out,const Complex& c);//重定向的重载 返回值是一个ostream类的一个对象 这样可以连续输出cout<(const Complex& c1)const;
	bool operator<(const Complex& c1)const;
	friend ostream operator<<(ostream& out, const Complex& c);
private:
	double real;
	double imag;
};

//事实上 c1+c2 等价于 c1.operator(c2);
Complex Complex::operator+(const Complex& c1)const
{
	Complex temp;
	temp.real = real + c1.real;
	temp.imag = imag + c1.imag;
	return temp;
	//return Complex(real+c1.real,imag+c1.imag)   这种写法也很好
}
Complex Complex::operator-(const Complex& c1)const
{
	Complex temp;
	temp.real = real - c1.real;
	temp.imag = imag - c1.imag;
	return temp;
}
Complex Complex:: operator*(const Complex& c1)const{
	Complex temp;
	temp.real = real * c1.real;
	temp.imag = imag * c1.imag;
	return temp;
}
Complex Complex:: operator/(const Complex& c1)const
{
	Complex temp;
	temp.real = real / c1.real;
	temp.imag = imag / c1.imag;
	return temp;
}
Complex Add(const int a,const Complex &c1)
{
	Complex temp;
	temp.real = a + c1.real;
	temp.imag = c1.imag;
	return temp;
}
Complex Jian(const int a,const Complex &c1)
{
	Complex temp;
	temp.real = c1.real - a;
	temp.imag = c1.imag;
	return temp;
}
Complex Chen(const int a,const Complex &c1)
{
	Complex temp;
	temp.real = c1.real * a;
	temp.imag = c1.imag;
	return temp;
}
Complex Chu(const int a,const Complex &c1)
{
	Complex temp;
	temp.real = c1.real / a;
	temp.imag = c1.imag;
	return temp;
}

Complex Complex::operator-()
{
	return Complex(-real, -imag);
}
Complex Complex::operator++()
{
	++real;
	++imag;
	return Complex(real, imag);
}
Complex Complex::operator++(int)
{
	Complex temp(*this);//先取出值 作为临时的值 给temp 再自增 传回去的是 temp;也就是原来没自增前的值 
	real++;
	imag++;
	return temp;
}
bool Complex::operator==(const Complex& c1)const
{
	return real == c1.real&&imag == c1.imag;
}
bool Complex::operator!=(const Complex& c1)const
{
	return real != c1.real && imag != c1.imag;
}
bool Complex::operator>(const Complex& c1)const
{
	return real > c1.real && imag > c1.imag;
}
bool Complex:: operator<(const Complex& c1)const
{
	return real < c1.real && imag c3:"<<(c4 > c3)<


你可能感兴趣的:(c++学习笔记--由复数类看运算符重载)