所谓重载,就是重新赋予新的含义。函数重载就是对一个已有的函数赋予新的含义,使之实现新的功能。
而运算符重载的方法是定义一个重载运算符的函数,在需要执行被重载的运算符时,系统就自动调用该函数,以实现相应的运算。运算符重载时通过定义函数实现的,运算符重载实质上是函数的重载。
重载运算符的函数一般格式如下:
例如我们重载运算符+,如下:
int operator+(int a,int b)
{
return (a-b);
}
举个例子:实现复数加法
(3,4i)+(5,-10i)=(8,-6i)
不用重载:
#include <iostream>
using namespace std;
class Complex
{
public:
Complex();
Complex(double r, double i); //带参数的构造函数
Complex complex_add(Complex &d);
void print();
private:
double real;
double imag;
};
Complex::Complex()
{
real = 0;
imag = 0;
}
Complex::Complex(double r, double i)
{
real = r;
imag = i;
}
Complex Complex::complex_add(Complex &d)
{
Complex c;
c.real = real + d.real;
c.imag = imag + d.imag;
return c;
}
void Complex::print()
{
cout << "(" << real << "," << imag << "i)\n";
}
int main()
{
Complex c1(3, 4), c2(5, -10), c3;
c3 = c1.complex_add(c2);
cout << "c1 = ";
c1.print();
cout << "c2 = ";
c2.print();
cout << "c1 + c2 = ";
c3.print();
return 0;
}
使用运算符重载:
#include <iostream>
using namespace std;
// 演示对运算符"+"进行重载达到目的!
class Complex
{
public:
Complex();
Complex(double r, double i); //带参数的构造函数
Complex operator+(Complex &d); //运算符重载
void print();
private:
double real;
double imag;
};
Complex::Complex()
{
real = 0;
imag = 0;
}
Complex::Complex(double r, double i)
{
real = r;
imag = i;
}
Complex Complex::operator+(Complex &d)
{
Complex c;
c.real = real + d.real;
c.imag = imag + d.imag;
return c;
}
void Complex::print()
{
cout << "(" << real << "," << imag << "i)\n";
}
int main()
{
Complex c1(3, 4), c2(5, -10), c3;
c3 = c1 + c2;
cout << "c1 = ";
c1.print();
cout << "c2 = ";
c2.print();
cout << "c1 + c2 = ";
c3.print();
return 0;
}
我们在声明Complex类的时候对运算符进行了重载,使得这个类在用户编程的时候可以完全不考虑函数是如何实现的,直接用+,-,*,/ 进行复数的运算即可。
其实还可以:
Complex Complex::operator+(Complex &2)
{
return Complex(real + c2.real, imag + c2.imag);
}
一些规则:
(1)C++不允许用户自己定义新的运算符,只能对已有的C++运算符进行重载
(2)除了对以下运算符不允许重载外,其他运算符允许重载:
--- .(成员访问运算符)
--- .*(成员指针访问运算符)
--- ::(域运算符)
--- sizeof (尺寸运算符)
--- ?:(条件运算符)
(3) 重载不能改变运算符运算对象(操作数)个数
(4) 重载不能改变运算符的优先级别
(5) 重载不能改变运算符的结合性
(6) 重载运算符的函数不能有默认参数
(7) 重载运算符必须和用户定义的自定义类型的对象一起使用,其参数至少应该有一个是类对象或类对象的引用。(也就是说,参数不能全部都是C++的标准类型,这样约定是为了防止用户修改用于标准类型结构的运算符性质)。
课后作业:
重载运算符"+","-","*","/"实现有理数的加减乘除运算。
有理数:任何可以用分数来表示的就是有理数