这里定义一个复数的类,并演示了它的用法
复数类 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 <iostream>
#include "complex.h"
using namespace std;
//默认构造函数
COMPLEX::COMPLEX(double r, double i)
{
real = r;
image = i;
cout<<"Default Constructing real: "<<r<<", image: "<<i<<" .\n";
return;
}
//拷贝构造函数
COMPLEX::COMPLEX(const COMPLEX &other)
{
real = other.real;
image = other.image;
cout<<"Copy Constructing real: "<<other.real<<", image: "<<other.image<<" .\n";
return;
}
//析构函数
COMPLEX::~COMPLEX()
{
cout<<"Destructing real: "<<real<<", image: "<<image<<" .\n";
return;
}
//打印复数
void COMPLEX::print()
{
cout<<real;
if (image > 0)
{
cout<<"+"<<image<<"i";
}
else if (image < 0)
{
cout<<image<<"i";
}
cout<<"\n";
return;
}
//重载加法运算符(二元)
COMPLEX COMPLEX::operator +(const COMPLEX &other)
{
COMPLEX temp;