实现C++类中对于前置++,后置++的重载

建立一个复数类,在类中实现构造函数、析构函数、拷贝构造和运算符重载

在运算符重载的实现过程中,可以发现,前置++和后置++在实现上有区别

由于前置++是先实现++,再进行使用,所以在实现过程中比较简单

而后置++需要先使用,再进行++操作


在以下程序中,实现了几个默认成员函数和前置++与后置++


#include 
   
   
    
    
using namespace std;

class Complex
{
private:
	double _real;
	double _image;
public:
	Complex(double real=0.0, double image=0.0)     //构造函数
	{
		_real = real;
		_image = image;
		cout << "Complex()" << endl;
	}
	~Complex()     //析构函数
	{
		cout << "~Complex" << endl;
	}
	Complex(Complex &com)   //拷贝构造函数
	{
		_real = com._real;
		_image = com._image;
		cout << "Complex(Complex& com)" << endl;
	}
	void Display()
	{
		cout << _real << "+" <<"("<< _image << "i)" << endl;
	}
	Complex operator+(Complex &com)   //加号重载
	{
		Complex tmp;
		tmp._real = _real + com._real;
		tmp._image = _image + com._image;
		return tmp;
	}
	Complex Add(Complex& com)   //加号
	{
		Complex tmp;
		tmp._real = _real + com._real;
		tmp._image = _image + com._image;
		return tmp;
	}
	Complex operator-(Complex &com)  //减号重载
	{
		Complex tmp;
		tmp._real = _real - com._real;
		tmp._image = _image - com._image;
		return tmp;
	}
	Complex& operator=(Complex& com)   //赋值运算符的重载
	{
		if (this != &com)
		{
			_real = com._real;
			_image = com._image;
		}
		return *this;   //返回引用
	}
	Complex& operator+=(Complex& com)     //加等重载
	{
		_real += com._real;
		_image += com._image;
		return *this;
	}
	Complex& operator-=(Complex& com)    //减等重载
	{
		_real -= com._real;
		_image -= com._image;
		return *this;
	}

	Complex& operator++()   //前置++
	{
		_real = _real + 1;
		_image = _image + 1;
		return *this;
	}
	Complex operator++(int)     //后置++
	{
		Complex cmp(*this);
		_real++;
		_image++;
		return cmp;
	}

};

int main()
{
	Complex C1(3.0, 3.0);
	Complex C2(3.0, 3.0);
	C1++.Display();
	C1.Display();
	(++C1).Display();
	C1.Display();
	return 0;
}
   
   



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值