一、介绍
- 运算符重载指的是对运算符的重新定义,使其支持特定类型的数据计算
- 所谓重载,就是赋予新的含义
- 函数重载(Function Overloading)可以让一个函数名有多种功能,在不同情况下进行不同的操作。
- 运算符重载(Operator Overloading)也是一个道理,同一个运算符可以有不同的功能
二、运算符重载的格式
函数的返回值类型 operator 运算符 (函数参数列表){}
- 函数名为:operator 运算符, 除此之外和普通函数其他一模一样
- complex operator + (complex b) 至于operator和运算符之间是否有空格不影响
- c = a + b c = a.operator+(b) 这就是函数调用啊
- 对象a 调用函数 operator+ 传入参数b
- return 语句 会创建一个临时对象,这个对象没有名称,是一个匿名对象。在创建临时对象过程中调用构造函数,return 语句将该临时对象作为函数返回值
三、配合代码理解重载
方式一: 类中重载+
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
//实现复数的+- 实数,虚数
class Complex
{
private:
double m_a, m_b;
public:
Complex(double m_a, double m_b): m_a(m_a),m_b(m_b){}
Complex(): m_a(0),m_b(0){}
Complex operator + (const Complex &A) const;
void show(Complex * c);
};
inline void Complex::show(Complex * c){
cout << c->m_a << " " << c->m_b << endl;
}
inline Complex Complex::operator +(const Complex &A) const
{
// Complex c;
// c.m_a = m_a + A.m_a;
// c.m_b = m_b + A.m_b;
// return c;
return Complex(m_a + A.m_a, m_b + A.m_b);
}
int main()
{
Complex a(2,3), b(1.5,3.2),c;
c = a + b;
c.show(&c);
return 0;
}
方式二:全局函数 重载 +
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
//实现复数的+- 实数,虚数
class Complex
{
private:
double m_a, m_b;
public:
Complex(double m_a, double m_b): m_a(m_a),m_b(m_b){}
Complex(): m_a(0),m_b(0){}
friend Complex operator +(const Complex &A, const Complex &B);
void show(Complex * c);
};
inline void Complex::show(Complex * c){
cout << c->m_a << " " << c->m_b << endl;
}
Complex operator +(const Complex &A, const Complex &B)
{
return Complex(A.m_a + B.m_a, A.m_b+B.m_b);
}
int main()
{
Complex a(2,3), b(1.5,3.2),c;
c = a + b;
c.show(&c);
return 0;
}
总结:
- 运算符重载其实就是定义一个函数,在函数体内实现想要的功能,当用到该运算符时,编译器会自动调用这个函数.
- 也就是说,运算符重载是通过函数实现的,它本质上是函数重载。
- 返回值类型 operator 运算符名称 (形参表列){}
- operator是关键字,专门用于定义重载运算符的函数。我们可以将operator 运算符名称这一部分看做函数名,对于上面的代码,函数名就是operator+
- 运算符重载函数除了函数名有特定的格式,其它地方和普通函数并没有区别。
- c3 = c1.operator+(c2);
- c3 = operator+(c1, c2);
- 当执行c3 = c1 + c2;语句时,编译器检测到+号左边(+号具有左结合性,所以先检测左边)是一个 complex 对象,就会调用成员函数operator+(),c3 = c1.operator+(c2);
- 当执行c3 = c1 + c2;语句时,编译器检测到+号两边都是 complex 对象,就会转换为类似下面的函数调用, c3 = operator+(c1, c2);
参考:
- http://c.biancheng.net/cpp/biancheng/view/3011.html
9501

被折叠的 条评论
为什么被折叠?



