temp.real = real + other.real;
temp.image = image + other.image;
cout<<"----- operator x + y start -----.\n";
cout<<"this->real: "<<real<<", this->image: "<<image<<" .\n";
cout<<"other.real: "<<other.real<<", other.image: "<<other.image<<" .\n";
cout<<"temp.real: "<<temp.real<<", temp.image: "<<temp.image<<" .\n";
cout<<"----- operator x + y end -----.\n";
return temp;
}
//重载减法运算符(二元)
COMPLEX COMPLEX::operator -(const COMPLEX &other)
{
COMPLEX temp;
temp.real = real - other.real;
temp.image = image - other.image;
cout<<"----- operator x - y start -----.\n";
cout<<"this->real: "<<real<<", this->image: "<<image<<" .\n";
cout<<"other.real: "<<other.real<<", other.image: "<<other.image<<" .\n";
cout<<"temp.real: "<<temp.real<<", temp.image: "<<temp.image<<" .\n";
cout<<"----- operator x - y end -----.\n";
return temp;
}
//重载求负运算符(一元)
COMPLEX COMPLEX::operator -()
{
COMPLEX temp;
temp.real = -real;
temp.image = -image;
cout<<"----- operator -x start -----.\n";
cout<<"this->real: "<<real<<", this->image: "<<image<<" .\n";
cout<<"temp.real: "<<temp.real<<", temp.image: "<<temp.image<<" .\n";
cout<<"----- operator -x end -----.\n";
return temp;
}
//重载赋值运算符(二元)
COMPLEX COMPLEX::operator =(const COMPLEX &other)
{
cout<<"----- operator x = y start -----.\n";
cout<<"other.real: "<<other.real<<", other.image: "<<other.image<<" .\n";
cout<<"this->real: "<<real<<", this->image: "<<image<<" .\n";
real = other.real;
image = other.image;
cout<<"other.real: "<<other.real<<", other.image: "<<other.image<<" .\n";
cout<<"this->real: "<<real<<", this->image: "<<image<<" .\n";
cout<<"----- operator x = y end -----.\n";
return *this; //这里返回的是当前对象,*this表示取指向当前对象指针的值,也就是当前对象
//实际上这里返回的是一个当前对象的副本,该对象副本通过拷贝构造函数创建
}
-------------------------------------------------------
演示复数类 COMPLEX 的用法文件:main.cpp
-------------------------------------------------------
#include <iostream>
#include "complex.h"
using namespace std;
int main()
{
cout<<"COMPLEX c1(1,2);\n";
COMPLEX c1(1,2); //定义一个值为 1+2i 的复数
cout<<"COMPLEX c2(2);\n";
COMPLEX c2(2); //定义一个值为 2 的复数
cout<<"COMPLEX c3(c1);\n";
COMPLEX c3(c1); //用拷贝构造函数创建一个值与c1相同的新复数c3