运算符重载训练

#include<iostream>
using namespace std;
class Complex {
public:
	friend ostream& operator<<(ostream& cout, Complex& c);
	Complex() {};
	Complex(int x, int y) {
		this->a = x;
		this->b = y;
	}
	//重载前置++运算符
	Complex& operator++() {
		this->a++;
		this->b++;
		return *this;
	}

	//重载后置++运算符
	Complex operator++(int) {
		Complex temp = *this;
		a++;
		b++;
		return temp;
	}

	/*
	void  operator<<(ostream &cout) {
		cout << "a=" << a << endl;
		cout << "b=" << b << "i" << endl;
	}
	*/
	Complex operator+(Complex& c2) {
		Complex temp;
		temp.a = this->a + c2.a;
		temp.b = this->b + c2.b;
		return temp;
	}
	
	void display() {
		cout << "a=" << a << endl;
		cout << "b=" << b << "i" << endl;
	}
private:
	int a;
	int b;
};

ostream& operator<<(ostream& cout, Complex &c) {//本质是operator<<(cout,p),简化的话就变成cout<<p
	cout << "利用全局函数重载左移运算符" << endl;
	cout << "a=" << c.a << " " << "b=" << c.b << 'i' << endl;
	return cout;
}

int main() {
	Complex c1(10, 20);
	Complex c2(1, 2);
	Complex c3 = c1 + c2;
	c3.display();


	//成员函数本质调用是
	c3 = c1.operator+(c2);
	
	//全局函数本质调用是
	//c3 = operator+(c1, c2);
	//c3 << cout;
	cout << c3;
	cout << c3 << endl;
	
	cout << "现在是前置++" << endl;
	cout << ++c3 << endl;
	cout << ++(++c3) << endl;
	
	/*
	cout << "现在是后置++" << endl;
	cout << c3++ << endl;
	cout << (c3++)++ << endl;
	*/

	//会报错,因为你已经重载过<<左移运算符了,它的操作对象是一个类,而后置++返回的是一个数

	

	c3++;
	cout << c3 << endl;
	++c3;
	cout << c3 << endl;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值