P211_成员函数和友元函数完成一元运算符重载

#include <iostream>
using namespace std;

class Complex
{
	friend Complex& operator++(Complex &c1);
private:
	int a;
	int b;
public:
	Complex& operator--()
	{
		this->a--;
		this->b--;
		return *this;
	}
	Complex(int a = 0, int b = 0)
	{
		this->a = a;
		this->b = b;
	}
	void printCom()
	{
		cout << a << "+" << b << "i" << endl;
	}
	//成员函数 法 实现 - 运算符重载
	Complex operator-(Complex &c2)
	{
		Complex tmp(this->a - c2.a, this->b - c2.b);
		return tmp;
	}
};
Complex& operator++(Complex &c1)
{
	c1.a++;
	c1.b++;
	return c1;
}

/*
全局函数、类成员函数方法实现运算符重载步骤:
1)要承认操作符重载是一个函数,写出函数名称
2)根据操作数,写出函数参数
3)根据业务,完善函数返回值(看函数是返回引用 还是指针 元素),及实现函数业务
*/

int main()
{
	Complex c1(1, 2);

	
	//前置++运算符  用全局函数实现
	//Complex& operator++(Complex &c1);  //c1的属性发生变化,返回一个c1的本身比较合适
	++c1;
	c1.printCom();

	//前置--操作符  成员函数方法
	--c1;
	c1.printCom();
	//c1.operator--();
	// Complex& operator--()


	

	return 0;

}

猜你喜欢

转载自blog.csdn.net/weixin_41983807/article/details/87801100