运算符重载

运算符重载可以将改变本来运算符的数据类型
有两种形式:重载为类的友元函数或成员函数
1.重载为友元函数:
friend type operator 运算符( )

#include <bits/stdc++.h>
using namespace std;
class Complex {
	public:
		Complex() {real = 0, imag = 0;}
		Complex(double r, double i) {real = r, imag = i;}
		void display();
		friend Complex operator + (Complex c1, Complex c2);
	private:
		double real;
		double imag;
};
void Complex::display() {
	cout << "(" << real << "," << imag << "i"<< ")" <<endl;
}
Complex operator + (Complex c1, Complex c2) {
	return Complex(c1.real + c2.real, c1.imag + c2.imag);
}
int main () {
	Complex c1(3, 4), c2(5, -10), c3;
	c3 = c1 + c2;
	cout << "c1 = "; c1.display();
	cout << "c2 = "; c2.display();
	cout << "c1 + c2 = "; c3.display();
	return 0;
	}

2.重载为类的成员函数
type operator 运算符( )
参数表中的参数数目是重载运算符的操作数-1,如果是双目运算符,左操作数是当前对象本身的数据,右操作数为参数表中的操作数

#include <bits/stdc++.h>
using namespace std;
class Complex {
	public:
		Complex() {real = 0, imag = 0;}
		Complex(double r, double i) {real = r, imag = i;}
		Complex operator + (Complex c2);
		void display();
	private:
		double real;
		double imag;
};
Complex Complex :: operator +(Complex c2) {
	return Complex(real + c2.real, imag + c2.imag); 
}
void Complex::display() {
	cout << "(" << real << "," << imag << "i"<< ")" <<endl;
}
int main () {
	Complex c1(3, 4), c2(5, -10), c3;
	c3 = c1 + c2;
	cout << "c1 = "; c1.display();
	cout << "c2 = "; c2.display();
	cout << "c1 + c2 = "; c3.display();
	return 0;
	}
posted @ 2022-04-23 17:02  misasteria  阅读(40)  评论(0编辑  收藏  举报