#pragma once
#ifndef COMPLEX0_H_
#define COMPLEX0_H_
#include<iostream>
class Complex
{
private:
double real;
double imgn;
public:
Complex();
Complex(double a, double b);
~Complex();
Complex operator+(const Complex & a) const;
Complex operator-(const Complex & a) const;
Complex operator~();
Complex operator*(double c);
Complex operator*(const Complex & a) const;
//friend
friend Complex operator*(const double c, const Complex & a);
friend std::ostream & operator<<(std::ostream & os, const Complex &a);//operator后面别打空格
friend std::istream & operator>>(std::istream & os, Complex &a);//cin是在istream里
};
#endif // !COMPLEX0_H_
//总结,如果在第二个构造函数里写了double n =0, double b = 0;就不用写complex(),两个是等价的,会存在歧义
//所以尽量不要在构造函数参数里写 = 0;因为会产生歧义,老实用complex()和第二个构造函数就好
//凡是不用改变的都设成const
---------------------------------
#include"complex0.h"
Complex::Complex()
{
real = imgn = 0;
}
Complex::Complex(double n1, double n2)
{
real = n1;
imgn = n2;
}
Complex Complex::operator+(const Complex & a) const
{
Complex temp;
temp.real = real + a.real;
temp.imgn = imgn + a.imgn;
return temp;
/*return Complex(real + a.real, imgn + a.imgn);*///直接调用构造函数//要习惯于用这个简化语句
//一般就用最后一条语句,等价于前面三条,调用构造函数会产生一个临时对象,赋值给左边
}
Complex Complex::operator-(const Complex & a) const
{
Complex temp;
temp.real = real - a.real;
temp.imgn = imgn - a.imgn;
return temp;
}
Complex Complex::operator*(const Complex & a) const
{
Complex temp;
temp.real = real * a.real + imgn * a.imgn;
temp.imgn = real * a.imgn + imgn * a.real;
return temp;
}
Complex Complex::operator~()
{
imgn = 0 - imgn;
return *this;
}
Complex Complex::operator*(double c)
{
return Complex(c * real, c * imgn);
}
//friend
Complex operator*(const double c, const Complex & a)//别打::因为友元不在类里面,虽然是在类里面声明
{
return Complex(c * a.real, c * a.imgn);
}
std::ostream & operator<< (std::ostream & os, const Complex &a)
{
os << "is " << "( " << a.real << ", " << a.imgn << "i )";
return os;
}
std::istream & operator >> (std::istream & os, Complex & a)//cin在istream里
{
std::cout << "real: ";
os >> a.real;
std::cout << "imaginary: ";
os >> a.imgn;
return os;
}
Complex::~Complex()
{
}