C++PrimerPlus第十一章类的使用 :重写练习七,解决重复造轮子的问题

在第十一章练习七中,为解决重复造轮子的问题。我们先看一下代码的实现

#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,多练习多思考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值