算数操作符

实现算数操作符 + 、 - 、自增运算符++等一般有两种方法:
第一种方法:类操作符
此时,操作符函数是类的成员函数。
第二种方法:全局操作符
此时,重载的是全局操作符,需要把一个操作符函数(类似于全局函数)声明为类的友元。

#include<iostream>
using namespace std;
class Complex {
public:
	Complex() {//构造函数初始化复数为0+0i
		this->imag = 0;
		this->real = 0;
	};
	Complex operator + (const Complex& other);//声明复数加复数
	Complex operator + (int n);;//声明复数加整数
	friend Complex operator + (int a, const Complex& b);//声明整数加复数
	friend Complex operator - (const Complex& a, const Complex& b);//声明复数减复数
	friend Complex operator - (int a, const Complex& b);//声明整数减复数
	friend Complex operator - (const Complex& a, int b);//声明复数减整数
	Complex& operator ++ () {//前置++
		this->real++;
		this->imag++;
		return *this;
	}
	Complex& operator ++ (int) {//后置++
		Complex a = *this;
		a.real++;
		a.imag++;
		return a;
	}
	friend ostream& operator << (ostream&, Complex&);//声明重载运算符“<<”
	friend istream& operator >> (istream&, Complex&);//声明重载运算符“>>”
private:
	int real;//复数的实部
	int imag;//复数的虚部
};
Complex Complex::operator + (const Complex& other) {//复数加复数的实现
	this->real = this->real + other.real;
	this->imag = this->imag + other.imag;
	return *this;
};
Complex Complex::operator + (int n) {//复数加整数的实现
	this->real = this->real + n;
	return *this;
}
Complex operator + (int a, const Complex& b)//整数加复数的实现
{
	Complex result;
	result.real = a + b.real;
	return result;
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值