因为涉及到输入流和输出流的重载,这里先介绍一下输入流和输出流的重载方法:
struct Vector
{
int x;
int y;
};
我们要在输出流中直接输出类,比如(1,2),(3,4),那么我们该怎么做呢
这个时候我们要重载输出流:
ostream& operator<<(ostream& o, Vector v)
{
return o << "(" << v.x << ", " << v.y << ")";
}
这样就能按照指定格式输出了,
实数具有实部和虚部,我们首先定义类的初始化变量和构造析构函数:
class Complex
{
private:
double real;
double image;
public:
Complex(const Complex& complex) :real{ complex.real }, image{ complex.image } {
}
Complex(double Real = 0, double Image = 0) :real{ Real }, image{ Image } {
}
之后是实数的计算,我们可以直接通过重载计算符号来把实数计算公式封装到里面
//加号的重载
Complex operator+(const Complex &obj) {
Complex res;
res.real = this->real + obj.real;
res.image = this->image + obj.image;
return res;
}
//减号的重载
Complex operator-(const Complex &obj) {
Complex res;
res.real = this->real - obj.real;
res.image = this->image - obj.image;
return res;
}
//乘号重载
Complex operator*(const Complex &obj) {
Complex res;
res.real = (this->real*obj.real) - (this->image*obj.image);
res.image = (this->image*obj.real) + (this->real*obj.image);
return res;
}
//除号的重载
Complex operator/(const Complex &obj) {
Complex res;
res.real = (((this->real*obj.real) + (this->image*obj.image)) / (obj.real*obj.real + obj.image*obj.image));
res.image = (((this->image*obj.real) - (this->real*obj.image)) / (obj.real*obj.real + obj.image*obj.image));
return res;
}
计算完毕后,我们要输出变量,肯定是整个实数按规定格式输出的吧,为了方便,我们直接重载输入流和输出流,这样就能按照我们指定的格式输出了
//输出流重载
ostream& operator<<(ostream& O, const Complex&obj) {
return O << "(" << obj.real << (obj.image>0?"+":"") << obj.image << "i" << ")";
}
//输入流重载
istream& operator>>(istream& I, Complex&obj) {
I >> obj.real >> obj.image;
return I;
}
切记,如果重载写在外面,一定要在类里面声明友元,否则我们无法调用类中的private成员变量
friend ostream& operator<<(ostream& O, const Complex&obj);
friend istream& operator>>(istream& I, Complex&obj);
补充:根据栈上的对象不能返回引用,因为operator+ - * /都创建了一个局部变量,所以不能返回引用
operator=,由于变量在堆中,所以要返回引用