运算符重载(一)

1.举例说明什么是运算符重载:

int i1 = 1, i2 = 2;
int isum = i1 + i2;

double d1 = 1.1, d2 = 2.2;
double dsum = d1 + d2;

long l1 = 1, l2 = 2;
long lsum = l1 + l2;

计算机对整数、双精度数、长整型数据的加法操作过程不同,C++已经对+进行了重载。

同理:<<和>> 位移运算符 流插入(左右)-------(提取)运算符,在不同的场合使用作用不同。
C++系统对<<和>>进行了重载,放在头文件stream中,因此如果要将它们用作流运算符的话,要:
 
 
#include<iostream>
using namespace std;

2.运算符重载的方法
运算符重载的方法是定义一个重载运算符的函数,在需要执行被重载的运算符时,系统就会自动调用该函数,以实现相应的运算。运算符重载实质上是函数的重载。 

重载运算符的函数格式:
函数类型 operator 运算符名称(形参列表){对运算符的重载处理}

举例说明:复数相加
普通成员函数实现方法:
#include <iostream>
using namespace std;

class Complex{
public:
	Complex(){real = 0; imag = 0;}
	Complex(double r, double i){real = r; imag = i;}
	Complex complex_add(Complex& c2);
	void display();

private:
	double real;
	double imag;
};

Complex Complex::complex_add(Complex& c2){
	return Complex(real+c2.real, imag+c2.imag);
}

void Complex::display(){
	cout<<"("<<real;
	if (imag>0){cout<<"+";}
	cout<<imag<<"i)"<<endl;
}

int main(){
	Complex c1(3,4), c2(5,-10), c3;
	c3 = c1.complex_add(c2);
	cout<<"c1=";c1.display();
	cout<<"c2=";c2.display();
	cout<<"c3=";c3.display();
	return 0;
}

重载运算符方法:

 #include <iostream>
 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;
 	if (imag>0){cout<<"+";}
 	cout<<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<<"c3=";c3.display();
 	return 0;
 }

在将运算符+重载为类的成员函数后,C++编译系统将c1+c2解释为:

c1.operator+(c2);


猜你喜欢

转载自blog.csdn.net/weixin_39664459/article/details/80353240