这里定义一个复数的类,并演示了它的用法
复数类 COMPLEX 的定义头文件:complex.h
-------------------------------------------------------
class COMPLEX
{
public:
COMPLEX(double r=0, double i=0); //默认构造函数
COMPLEX(const COMPLEX &other); //拷贝构造函数
~COMPLEX(); //析构函数
void print(); //打印复数
COMPLEX operator +(const COMPLEX &other); //重载加法运算符(二元)
COMPLEX operator -(const COMPLEX &other); //重载减法运算符(二元)
COMPLEX operator -( ); //重载求负运算符(一元)
COMPLEX operator =(const COMPLEX &other); //重载赋值运算符(二元)
protected:
double real; //复数的实部
double image; //复数的虚部
};
-------------------------------------------------------
复数类 COMPLEX 的实现文件:complex.cpp
-------------------------------------------------------
#include
#include "complex.h"
using namespace std;
//默认构造函数
COMPLEX::COMPLEX(double r, double i)
{
real = r;
image = i;
cout<<"Default Constructing real: "< return;
}
//拷贝构造函数
COMPLEX::COMPLEX(const COMPLEX &other)
{
real = other.real;
image = other.image;
cout<<"Copy Constructing real: "< return;
}
//析构函数
COMPLEX::~COMPLEX()
{
cout<<"Destructing real: "< return;
}
//打印复数
void COMPLEX::print()
{
cout< if (image > 0)
{
cout<<"+"< }
else if (image < 0)
{
cout< }
cout<<"\n";
return;
}
//重载加法运算符(二元)
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: "<image: "< cout<<"other.real: "< cout<<"temp.real: "< 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: "<image: "< cout<<"other.real: "< cout<<"temp.real: "< 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: "<image: "< cout<<"temp.real: "< cout<<"----- operator -x end -----.\n";
return temp;
}
//重载赋值运算符(二元)
COMPLEX COMPLEX::operator =(const COMPLEX &other)
{
cout<<"----- operator x = y start -----.\n";
cout<<"other.real: "< cout<<"this->real: "<image: "< real = other.real;
image = other.image;
cout<<"other.real: "< cout<<"this->real: "<image: "< cout<<"----- operator x = y end -----.\n";
return *this; //这里返回的是当前对象,*this表示取指向当前对象指针的值,也就是当前对象
//实际上这里返回的是一个当前对象的副本,该对象副本通过拷贝构造函数创建
}
-------------------------------------------------------
演示复数类 COMPLEX 的用法文件:main.cpp
-------------------------------------------------------
#include
#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
cout<<"\nc3.print();\n";
c3.print(); //打印c3原来的值
cout<<"\nc1 = c1 + c2 + c3;\n";
c1 = c1 + c2 + c3; //将c1加上c2再加上c3赋值给c1
cout<<"\nc2 = -c3;\n";
c2 = -c3; //将c3求负后赋