1、运算符重载:实质就是函数重载
1返回值类型 operator运算符(形参表) 2 3{ 4...... 5}
运算符重载为普通函数:

运算符重载为成员函数:

Note:重载成全局函数时操作数个数等于函数参数个数。
2、赋值运算符“=”的重载
赋值运算符两边的类型可以不匹配,此时我们需要重载赋值运算符“=”,且只能重载为成员函数。例如:
(1)把一个int型变量赋值给Complex对象
(2)把一个char*类型的字符串赋值给一个字符串对象
重载赋值运算符的意义:浅复制(浅拷贝),深复制(深拷贝)
浅:执行逐字节的复制工作。


深:将一个对象中指针变量指向的内容复制到另一个对象中指针成员对象指向的地方。


3、运算符重载为友元函数
成员函数不能满足使用要求;普通函数不能访问类的私有成员。这两种情况下需要把运算符重载为友元函数。
4、实例:可变长整型数组

1class CArray 2{ 3 int size; //数组元素的个数 4 int *ptr; //指向动态分配的数组 5public: 6 CArray(int s = 0); //s代表数组元素的个数,构造函数 7 CArray(CArray & a);~CArray(); 8 void push_back(int v); //用于在数组尾部添加一个元素v 9 CArray & operator=( const CArray & a);//用于数组对象间的赋值 10 int length() { return size; } //返回数组元素个数 11 int& CArray::operator[](int i) //返回值是什么类型? 12 {//用以支持根据下标访问数组元素, 13 //如n = a[i]和a[i] = 4; 这样的语句 14 return ptr[i]; 15 } 16};
Note:非引用的函数返回值不可以作为左值使用。 所以用int&
5、流插入/流提取运算符重载
1#include <stdio.h> 2#include <iostream> 3#include <string> 4#include <cstdlib> 5 6using namespace std; 7 8class Complex{ 9 double real; 10 double imag; 11public: 12 Complex(double i = 0, double j = 0):real(i), imag(j){}; 13 Complex(const Complex &c); 14 friend ostream & operator<<(ostream &o, Complex &c); 15 friend istream & operator>>(istream &i, Complex &c); 16}; 17Complex::Complex(const Complex &c) { 18 real = c.real; 19 imag = c.imag; 20} 21ostream & operator<<(ostream &o, Complex &c){ 22 o<<c.real<<"+"<<c.imag<<"i"<<endl; 23 return o; 24} 25istream & operator>>(istream &i, Complex &c){ 26 string s; 27 i>>s; 28 int pos = s.find("+",0); 29 string sTemp = s.substr(0,pos); 30 c.real = atof(sTemp.c_str());//atof库函数能将const char*指针只想的内容转换成float 31 sTemp = s.substr(pos+1, s.length()-pos-2); 32 c.imag = atof(sTemp.c_str()); 33 return i; 34} 35 36int main(int argc, char * argv[]){ 37 Complex k; 38 int n; 39 cin>>k>>n; 40 cout<<k<<","<<n<<endl; 41 return 0; 42}
6、自加/自减运算符
(1)前置作为一元运算符重载:
重载为成员函数:
1T & operator++(); 2T & operator--();
重载为全局函数:
1T & operator++(T &); 2T & operator--(T &);
++obj, obj.operator++(), operator++(obj) 都调用上述函数。
(2)后置作为二元运算符重载:
需要比前置多写一个参数,无具体意义,只是加以区别。
重载为成员函数:
1T operator++(int); 2T operator--(int);
重载为全局函数:
1T operator++(T &, int); 2T operator--(T &, int);
obj++, obj.operator++(0), operator++(obj,0) 都调用上述函数。
(3)
1operator int ( ) { return n; } 2Demo s; 3(int) s ; //等效于 s.int()
int 作为一个类型强制转换运算符被重载。
类型强制转换运算符重载时,
• 不能写返回值类型
• 实际上其返回值类型为类型强制转换运算符代表的类型
Note:
C++不允许定义新的运算符,
运算符重载不改变运算符的优先级,
以下运算符不能被重载: “.”, “.*”, “::”, “?:”, sizeof,
重载运算符(), [ ], ->或者赋值运算符=时, 重载函数必须声明为类的成员函数。