在第十一章练习七中,为解决重复造轮子的问题。我们先看一下代码的实现
#include"pe11_7.h"
#include<iostream>
using namespace std;
Complex::Complex(double a, double bi)
{
this->a = a;
this->bi = bi;
SetComplex();
}
void Complex::SetComplex(void)
{
this->comlex.a = this->a;
this->comlex.bi = this->bi;
}
void Complex::SetABi()
{
this->a = this->comlex.a;
this->bi = this->comlex.bi;
}
ostream& operator<<(ostream& os, const Complex& a)
{
os << "(" << a.a << "," << a.bi << "i)";
return os;
}
istream& operator>>(istream& is, Complex& a)
{
cout << "real: ";
is >> a.a;
if (!is)
{
is.ignore(numeric_limits<streamsize>::max(), '\n');
return (is);
}
cout << "imaginary: ";
is >> a.bi;
if (!is)
{
is.ignore(numeric_limits<streamsize>::max(), '\n');
}
return (is);
}
Complex Complex::operator+(Complex& a)
{
Complex temp;
temp.a = this->a + a.a;
temp.bi = this->bi + a.bi;
return temp;
}
Complex Complex::operator-(Complex& a)
{
Complex temp;
temp.a = this->a - a.a;
temp.bi = this->bi - a.bi;
return temp;
}
Complex Complex::operator*(Complex& a)
{
Complex temp;
temp.a = this->a * a.a - this->bi * a.bi;
temp.bi = this->a * a.bi + this->bi * a.a;
return temp;
}
Complex operator*(double n, Complex& a)
{
Complex temp;
temp.a = n*a.a;
temp.bi = n*a.bi;
return temp;
}
Complex operator~(Complex& a)
{
Complex temp;
temp.a = a.a;
temp.bi = -a.bi;
return temp;
}
在代码中,我们发现了很多重复的代码
Complex temp;
temp.a = this->a + a.a;
temp.bi = this->bi + a.bi;
return temp;
这段代码就是创建并复制,所以问题就转换为,用构造函数传参
Complex Complex::operator+(Complex& a)
{
return Complex(this.a+a.a,this.bi+a.bi);
}
同理
Complex Complex::operator-(Complex& a)
{
Complex temp;
temp.a = this->a - a.a;
temp.bi = this->bi - a.bi;
return temp;
}
改为
Complex Complex::operator-(Complex& a)
{
return Complex(this.a-a.a,this.bi-a.bi);
}
剩下4个用同样的方法,这样解决了重复造轮子的问题
·
·
·
·
这里还有一个问题,我们频繁的调用,构造函数,我们把构造函数也改一下
Complex::Complex(double a, double bi)
{
this->a = a;
this->bi = bi;
SetComplex();
}
我们改成内联函数,还要说明一下之前的Complex_t有点冗余,这里暂时不考虑,当然你喜欢的话可以保留,
Complex::Complex(double a, double bi){this.a = a,this.bi =bi}
内联函数就修改好了。
总结:
1,C++的程序能减少很多重复造轮子的问题。
2,C++程序能一直优化
3,多练习多思考