#include<iostream>
using namespace std;
class complex
{
public:
	complex() {
		real = 0;
		imag = 0;
	}
	void display();
	complex(int a, int b) :real(a), imag(b) {}
	friend complex operator +(complex& c1, complex& c2);//友元函数重载+ 无this 需要两个参数

	complex operator -(complex& c3);//成员函数重载- 有this指针 只用一个参数
	
	friend ostream & operator <<(ostream&, complex&);//只能友元函数重载流运算符号
	friend istream& operator >>(istream&, complex&);

	int real, imag;
};
complex complex::operator-(complex& c3) {

	return complex(real - c3.real, imag - c3.imag);//这是一个临时建立的对象,在建立时临时调用了构造函数。

}

ostream& operator <<(ostream& output, complex& c)
{
	output << c.real << ":" << c.imag << endl;
	return output;
	//output是ostream类对象的引用
}

istream& operator>>(istream& input, complex& c)
{
	input >> c.real >> c.imag;
	return input;
}

complex operator +(complex& c1, complex& c2)
{
	return complex(c1.real+c2.real,c1.imag+c2.imag);
}
void complex::display() {
	cout << this->real << ":" << this->imag << endl;
}
int main() {
	complex c1(1, 3), c2(3, 3),c3,c4,c5;
	cin >> c5;
	c3 = c1 + c2;
	c3.display();
	c4 = c2 - c1;
	cout << c4;
	cout << c5;
		return 0;

}
/*
* 重点!!
1.不能重载的运算符 . * :: sizeof ?:
2.重载不改变运算符个数,优先级别,结合性,不能有默认参数,
3.必须和定义的类型一起使用,参数至少要有一个是类对象
4.= 和 &无需重载就可以用
5.一般单目运算符用成员例如++  双目用友元 例如 +
6.流运算符只能用友元函数重载
7.= () [] -> 不能重载为友元函数
*/

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐