不使用
C++
标准库,自行设计并实现一个复数类
Complex
,使其满足如下要求:
数据成员
用来表示复数的实部
real
和虚部
imag
,实部、虚部,均为小数形式。
函数成员
构造函数
支持以下方式定义复数对象:
成员函数
get_real()
返回复数实部
get_imag()
返回复数虚部
show()
用于输出复数。要求以
3 + 4i
,
3
-
4i
这样的形式输出
add()
用于把一个复数加到自身,比如
c1.add(c2)
,相当于
c1 += c2
友元函数
add()
用于实现两个复数相加,返回复数。比如
c3 = add(c1, c2)
;
is_equal()
用于判断两个复数是否相等,返回
true/false
。比如
is_equal(c1, c2)
abs()
用于对复数进行取模运算
将类
Complex
的定义及友元函数实现,单独保存在文件
Complex.hpp
中。
使用
task3.cpp
中的代码,测试类
Complex
的各项接口是否正确。
#include "Complex.hpp"
#include <iostream>
int main()
{
using namespace std;
Complex c1(11, -4);
const Complex c2(4.5);
Complex c3(c1);
cout << "c1 = ";
c1.show();
cout << endl;
cout << "c2 = ";
c2.show();
cout << endl;
cout << "c2.imag = " << c2.get_imag() << endl;
cout << "c3 = ";
c3.show();
cout << endl;
cout << "abs(c1) = ";
cout << abs(c1) << endl;
cout << boolalpha;
cout << "c1 == c3 : " << is_equal(c1, c3) << endl;
cout << "c1 == c2 : " << is_equal(c1, c2) << endl;
Complex c4;
c4 = add(c1, c2);
cout << "c4 = c1 + c2 = ";
c4.show();
cout << endl;
c1.add(c2);
cout << "c1 += c2, " << "c1 = ";
c1.show();
cout << endl;
return 0;
}
#include<iostream>
#include<cmath>
using namespace std;
class Complex
{
public:
Complex(double a = 0,double b = 0):real{a},imag{b} {};
Complex(const Complex &c1);
~Complex() = default;
double get_real() const {return real;}
double get_imag() const {return imag;}
void show() const;
void add(Complex const &c1);
friend Complex add(Complex const&c1,Complex const&c2);
friend bool is_equal(Complex const&c1,Complex const&c2);
friend double abs(Complex const&c1);
private:
double real;
double imag;
};
Complex::Complex(const Complex &c1)
{
real = c1.real;
imag = c1.imag;
}
void Complex::show() const
{
if(imag == 0)
cout << real ;
else if(imag < 0)
cout << real <<" - "<< abs(imag) << "i" ;
else
cout << real <<" + "<< imag << "i" ;
}
void Complex::add(Complex const&c1)
{
real += c1.real;
imag += c1.imag;
}
Complex add(Complex const&c1,Complex const&c2)
{
Complex c3;
c3.real = c1.real + c2.real;
c3.imag = c1.imag + c2.imag;
return c3;
}
bool is_equal(Complex const&c1,Complex const&c2)
{
if(c1.real == c2.real&&c1.imag ==c2.imag)
return true;
return false;
}
double abs(Complex const&c1)
{
return sqrt(c1.real*c1.real + c1.imag*c1.imag);
}