C++ 重载实例:复数的运算操作

因为涉及到输入流和输出流的重载,这里先介绍一下输入流和输出流的重载方法:

struct Vector
{
	int x;
	int y;
};

我们要在输出流中直接输出类,比如(1,2),(3,4),那么我们该怎么做呢

这个时候我们要重载输出流:

ostream& operator<<(ostream& o, Vector v)
{
	return o << "(" << v.x << ", " << v.y << ")";
}

这样就能按照指定格式输出了,

 

 

实数具有实部和虚部,我们首先定义类的初始化变量和构造析构函数:

class Complex
{
private:
	double real;
	double image;
public:
	Complex(const Complex& complex) :real{ complex.real }, image{ complex.image } {

	}
	Complex(double Real = 0, double Image = 0) :real{ Real }, image{ Image } {

	}
	

之后是实数的计算,我们可以直接通过重载计算符号来把实数计算公式封装到里面

//加号的重载
	Complex operator+(const Complex &obj) {
		Complex res;
		res.real = this->real + obj.real;
		res.image = this->image + obj.image;

		return res;
	}
    //减号的重载
	Complex operator-(const Complex &obj) {
		Complex res;
		res.real = this->real - obj.real;
		res.image = this->image - obj.image;

		return res;
	}
	//乘号重载
	Complex operator*(const Complex &obj) {
		Complex res;
		res.real = (this->real*obj.real) - (this->image*obj.image);
		res.image = (this->image*obj.real) + (this->real*obj.image);
		return res;
	}

	//除号的重载
	Complex operator/(const Complex &obj) {
		Complex res;
		res.real = (((this->real*obj.real) + (this->image*obj.image)) / (obj.real*obj.real + obj.image*obj.image));
		res.image = (((this->image*obj.real) - (this->real*obj.image)) / (obj.real*obj.real + obj.image*obj.image));
		return res;
	}

计算完毕后,我们要输出变量,肯定是整个实数按规定格式输出的吧,为了方便,我们直接重载输入流和输出流,这样就能按照我们指定的格式输出了

//输出流重载
ostream& operator<<(ostream& O, const Complex&obj) {
	return O << "(" << obj.real << (obj.image>0?"+":"") << obj.image << "i" << ")";
}

//输入流重载
istream& operator>>(istream& I, Complex&obj) {
	I >> obj.real >> obj.image;
	return I;
}

切记,如果重载写在外面,一定要在类里面声明友元,否则我们无法调用类中的private成员变量

friend ostream& operator<<(ostream& O, const Complex&obj);
friend istream& operator>>(istream& I, Complex&obj);

补充:根据栈上的对象不能返回引用,因为operator+ - * /都创建了一个局部变量,所以不能返回引用

operator=,由于变量在堆中,所以要返回引用 

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值