一.运算符重载的概念理解
所谓运算符的重载,我们可以这样理解;我们知道C语言中,我们所使用的“+,-,*,/”等符号都是用于数学运算表达的,可以用于数值与非数值之间,还可以用于表达式和变量常量之间,其表达的含义各不相同,所以我们称这几个符号除了可以用于数学数值计算以外,我们还可以有其他含义,这就是运算符的重载。
例子说明:
在数学表达式中:
(1).a=b;表示a的数值等于b的数值;
在C语言编程中:
(2).a=b;表示把b的值赋给a;
在这里,“=”就有两个含义,我们称起为等号的重载。
二.运算符重载的例子演示
例题说明:
请用函数重载的方式计算两个复数的减法。
解法:
1.建立一个类Complex
,在声明一个构造函数Complex
,并在类内进行构造函数的初始化,还需定义一个类的成员函数display
用于计算这一步骤环节。
2.类的私有数据存储real
和imag
,分别存储复数的实数
和虚数
。
3.在public
公有数据中声明一个运算符重载函数,其关键字为operator
,声明方式如下:
Complex operator-(Complex &c2);
类名 operator 运算符号(类名 &形参);
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;
};
4.重载函数的定义:
Complex Complex::operator-(Complex &c2)
{
return Complex(real - c2.real, imag - c2.imag);
}
在return语句中,我们对形参接收的两个数值分别进行虚数相减虚数,实数相减实数。
real-c2.real
:实数减实数
imag-c2.imag
;虚数减虚数
5.构造函数的定义:
void Complex::display()
{
cout << "(" << real << "," << imag << "i)" << endl;
}
6.编写主函数:
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;
}
7.例题全部代码:
#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 << "," << 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;
}
8.执行结果:
三.总结
1.运算符的重载可以类比函数重载的思路去理解