用C++的操作符重载实现了复数的加乘。。。
#include "iostream.h"
class Complex // 声明复数类
{
private:
double real; // 实部
double image; // 虚部
public:
Complex ( double r, double i ); // 初始化
~Complex( void ); // 销毁
void setReal ( double r ); // 设置实数
void setImage( double i ); // 设置虚数
double getReal ( void ); // 获得实数
double getImage( void ); // 获得虚数
void displayComplex( void ); // 显示实数
const Complex operator +( Complex C ); // 复数相加
const Complex operator *( Complex &C ); // 复数相乘
};
int main( void )
{
Complex c1( 2, 3 ), c2( 0, 1 ), c3( 2, -1 ), c4( 0, 0 );
c1.displayComplex( );
cout << endl;
c2.displayComplex( );
cout << endl;
c3.displayComplex( );
cout << endl;
c4.displayComplex( );
cout << endl;
c4 = c1 + c2;
cout << "相加后: " << endl;
c4.displayComplex( );
cout << endl;
c4 = c1 * c3;
cout << "相乘后: " << endl;
c4.displayComplex( );
cout << endl;
return 0;
}
/* 定义复数类 */
/* 初始化复数 */
Complex::Complex( double r, double i )
{
real = r;
image = i;
}
Complex::~Complex( void )
{
return;
}
void Complex::setReal( double r )
{
this->real = r;
}
void Complex::setImage( double i )
{
this->image = i;
}
double Complex::getReal( void )
{
return this->real;
}
double Complex::getImage( void )
{
return this->image;
}
/* 显示复数 */
void Complex::displayComplex( void )
{
cout << "复数为: " << endl;
if ( real == 0 )
{
cout << image << endl;
}
else
{
cout << real << "*i";
if ( image == 0 )
{
return;
}
else if ( image > 0 )
{
cout << " + " << image << endl;
}
else
{
cout << " - " << -image << endl;
}
}
}
/* 复数相加 */
const Complex Complex::operator +( Complex C )
{
Complex RC( 0, 0 );
RC.setReal ( this->real + C.getReal( ) ); // 设置相加后的实数
RC.setImage( this->image + C.getImage( ) ); // 设置相加后的虚数
return RC; // 返回相加得到的复数
}
/* 复数相乘 */
const Complex Complex::operator *( Complex &C )
{
Complex RC( 0, 0 );
RC.setReal ( this->real * C.getImage( ) + this->image * C.getReal( ) ); // 设置相乘后的实数
RC.setImage( this->real * C.getReal( ) + this->image * C.getImage( ) ); // 设置相乘后的虚数
return RC; // 返回相加得到的复数
}
评论