1 C++预定义的运算符,只能用于基本数据类型的运算:整形、实型、字符型、逻辑型
2 数学上,两个复数可以直接进行+ - 运算。但C++中,直接将+ -运用于复数对象不允许。
3 目的:为了让对象也通过运算符进行运算。
eg:
complex_a和complex_b是两个复数对象:求两个复数的和,希望能直接写
complex_a + complex_b
4 定义:对已有的运算符(C++中预定义的运算符)赋予多重的含义,使得同一运算符作用于不同类型的数据时导致不同类型的行为。
5 目的:扩展C++中提供的运算符的适用范围,使之能作用于对象。
6 特点:
同一运算符,对不同类型的操作数,所发生的行为不同。
complex_a + complex_b 生成一个新的复数对象
5 + 4 = 9
7 运算符重载的实质就是函数重载
8 可以重载为普通函数,也可以重载成成员函数
9 把含有运算符的表达式转换成对运算符函数的调用。
10 把运算符的操作数转换成运算符函数的参数。
11 运算符被多次重载时,根据实参的类型决定调用那个运算符函数。
12 运算符重载形式:
返回值类型 operator 运算符(形参表)
{
…
}
13 eg(见本工程operator.cpp)
/**
* 运算符重载例子
*
* 减号是双目运算符
* 重载为成员函数时,参数个数为运算符目数减一
* 重载为普通函数时,参数个数为运算符目数
*
* 可以吧operator- operator+看作是函数名称
*
*
* */
#include <iostream>
using namespace std;
class Complex{
public:
double real, imag;
Complex(double r = 0.0, double i = 0.0):real(r), imag(i){}
// 被重载的 - 成员函数
Complex operator-(const Complex& c);
};
// 全局函数
Complex operator+(const Complex& a, const Complex& b)
{
return Complex(a.real + b.real, a.imag + b.imag); // 返回一个临时对象 类名(参数表):代表一个对象
}
Complex Complex::operator-(const Complex &c) {
return Complex(real - c.real, imag - c.imag); // 返回一个临时对象 当前对象:operator - 所作用的那个对象
}
int main()
{
Complex a(4, 4), b(1, 1), c;
c = a + b; // 等价于 c = operator+(a, b);
cout << c.real << "," << c.imag << endl;
cout << (a-b).real << "," << (a-b).imag << endl;
// a-b等价于a.operator-(b);
return 0;
}