所谓重载,就是重新赋予新的含义。函数重载是对一个已有的函数赋予新的含义,使之实现新功能。
其实运算符也可以重载,实际上,我们常常在不知不觉之中使用了运算符重载。
运算符重载的方法是定义一个重载运算符的函数,在需要执行被重载的运算符时,系统就自动调用该函数,以实现相应的运算。 也就是说,运算符重载是通过定义函数实现的。运算符重载实质上是函数的重载。
重载运算符的函数一般格式如下:
函数类型 operator 运算符名称(形参表列) { 对运算符的重载处理 }
例如我们可以重载运算符 + , 如下:
int operator+(int a, int b) { return (a – b); }
举个栗子:实现复数加法 (3, 4i)+ (5, -10i)= (8, -6i)
当我们还不知道重载,我们会这样做: complex.cpp
#include <iostream> 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() { std::cout << "(" << real << ", " << imag << "i)\n"; } int main() { Complex c1(3, 4), c2(5, -10), c3; c3 = c1.complex_add(c2); std::cout << "c1 = "; c1.print(); std::cout << "c2 = "; c2.print(); std::cout << "c1 + c2 = "; c3.print(); return 0; }
结果:
c1 = (3, 4i) c2 = (5, -10i) c1 + c2 = (8, -6i) 请按任意键继续. . .
当我们朦胧懂得了重载,我们会这样做: complex2.cpp
#include <iostream> // 演示对运算符"+"进行重载达到目的! 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() { std::cout << "(" << real << ", " << imag << "i)\n"; } int main() { Complex c1(3, 4), c2(5, -10), c3; c3 = c1 + c2; std::cout << "c1 = "; c1.print(); std::cout << "c2 = "; c2.print(); std::cout << "c1 + c2 = "; c3.print(); return 0; }
我们在声明 Complex 类的时候对运算符进行了重载,使得这个类在用户编程的时候可以完全不考虑函数是如何实现的,直接使用 +, -, *, / 进行负数的运算即可。 其实,我们还可以对运算符重载函数 operator+ 改写得更简练一些:
Complex Complex::operator+(Complex &c2) { return Complex(real+c2.real, imag+c2.imag); }
一些规则:
除了一下五个不允许重载外,其他运算符允许重载:
.(成员访问运算符)
.*(成员指针访问运算符)
::(域运算符)
sizeof(尺寸运算符)
?:(条件运算符)
重载不能改变运算符的结合性。
重载运算符的函数不能有默认的参数。
重载的运算符必须和用户定义的自定义类型的对象一起使用,其参数至少应该有一个是类对象或类对象的引用。(也就是说,参数不能全部都是C++的标准类型,这样约定是为了防止用户修改用于标准类型结构的运算符性质)。
运算符重载函数作为类友元函数:
原文:https://www.cnblogs.com/tianqizhi/p/10420929.html