【C++】类的运算符重载

  1. 运算符重载
    1. 主要作用:实现类对象之间的运算;
    2. 隐式调用和显式调用;
    3. 类内部进行运算符重载只需要一个参数,因为类对象本身就是一个参数;
    4. 规则:
      • 运算符重载不允许发明新的运算符;
      • 不能改变运算符操作对象的个数;
      • 运算符被重载后,其优先级和结合性不会改变;
      • 不能重载的运算符:
      • ​​​​​​

Complex.h

#ifndef COMPLEX_H
#define COMPLEX_H

class Complex{
public:
	Complex();
	Complex(int real,int img);
	~Complex();
//	friend Complex operator+ (Complex &a,Complex &b);
	Complex operator+ (Complex &a);
//	friend Complex operator- (Complex &a,Complex &b);
	Complex operator- (Complex &a);
	Complex operator++ ();
	Complex operator++ (int);
	Complex operator-- ();
	Complex operator-- (int);
	Complex operator= (Complex &a);
	void cprintf();
private:
	int real;
	int img;
};


#endif

Complex.cpp

#include "Complex.h"
#include <iostream.h>

Complex::Complex()
{
	this->real = 0;
	this->img = 0;
}
Complex::Complex(int real,int img)
{
	this->real = real;
	this->img = img;
}
Complex::~Complex()
{

}

void Complex::cprintf()
{
	cout<<"值为:"<<this->real<<"+"<<this->img<<endl;
}

Complex Complex::operator+ (Complex &a)
{
	this->real += a.real;
	this->img += a.img;
	return *this;
}

Complex Complex::operator- (Complex &a)
{
	this->real -= a.real;
	this->img -= a.img;
	return *this;
}

Complex Complex::operator++ ()//前置++
{
	this->real ++;
	this->img ++;
	return *this;
}
Complex Complex::operator++ (int)//后置++
{
	Complex a = *this;
	this->real ++;
	this->img ++;
	return a;
}
Complex Complex::operator-- ()//前置--
{
	this->real --;
	this->img --;
	return *this;
}
Complex Complex::operator-- (int)//后置--
{
	Complex a = *this;
	this->real --;
	this->img --;
	return a;
}
Complex Complex::operator= (Complex &a)//=
{
	this->real = a.real;
	this->img = a.img;
	return *this;
}

调用:

    Complex a(1,2);
	Complex b(2,3);
	Complex c;

	c = a+b;
	c.cprintf();
	

	c = a-b;
	c.cprintf();

	a++;
	a.cprintf();

	++a;
	a.cprintf();

	a--;
	a.cprintf();

	--a;
	a.cprintf();

	a = b;
 	a.cprintf();

输出:

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿峰不想搬砖

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值