01 C++操作符重载
参考资料:
https://zhuanlan.zhihu.com/p/361116282
https://www.cnblogs.com/pandamohist/p/13838732.html
https://blog.csdn.net/liitdar/article/details/80656156
https://www.runoob.com/cplusplus/cpp-overloading.html
前言
C++ 允许在同一作用域中的某个函数和运算符指定多个定义,分别称为函数重载和运算符重载。
重载声明是指一个与之前已经在该作用域内声明过的函数或方法具有相同名称的声明,但是它们的参数列表和定义(实现)不相同。
当您调用一个重载函数或重载运算符时,编译器通过把您所使用的参数类型与定义中的参数类型进行比较,决定选用最合适的定义。选择最合适的重载函数或重载运算符的过程,称为重载决策。其实可以简单地将运算符重载简单理解为函数重载,不过重载的函数名称比较特殊。例如我需要对类中的加法进行重新定义,就可以通过重载operator +()
来完成。
注意:不是每一个运算符都可以重载!
下面是可重载的运算符列表:
双目算术运算符 | + (加),-(减),*(乘),/(除),% (取模) |
---|---|
关系运算符 | ==(等于),!= (不等于),< (小于),> (大于),<=(小于等于),>=(大于等于) |
逻辑运算符 | ||(逻辑或),&&(逻辑与),!(逻辑非) |
单目运算符 | + (正),-(负),*(指针),&(取地址) |
自增自减运算符 | ++(自增),–(自减) |
位运算符 | | (按位或),& (按位与),~(按位取反),^(按位异或),,<< (左移),>>(右移) |
赋值运算符 | =, +=, -=, *=, /= , % = , &=, |=, ^=, <<=, >>= |
空间申请与释放 | new, delete, new[ ] , delete[] |
其他运算符 | ()(函数调用),->(成员访问),,(逗号),[](下标) |
下面是不可重载的运算符列表:
- .:成员访问运算符
- .*, ->*:成员指针访问运算符
- :::域运算符
- sizeof:长度运算符
- ?::条件运算符
- #: 预处理符号
举例
通过下面这一个简单的例子可以很快帮你上手操作符重载。
#include <iostream>
using namespace std;
class Complex{
public:
Complex(double _real = 0.0, double _image = 0.0):real(_real), imag(_image){};
Complex(Complex& _C){
this->real = _C.real;
this->imag = _C.imag;
}
~Complex(){};
// 赋值
Complex& operator=(const Complex &c){
if(this == &c){
return *this;
}else{
this->real = c.real;
this->imag = c.imag;
return *this;
}
}
Complex operator+ (const Complex &c){
Complex B;
B.real = real + c.real;
B.imag = imag + c.imag;
return B;
}
Complex operator- (const Complex &c){
Complex B;
B.real = real - c.real;
B.imag = imag - c.imag;
return B;
}
inline bool operator==(const Complex &c) const {
return real == c.real && imag == c.imag;
}
inline bool operator!=(const Complex &c) const {
return real != c.real || imag != c.imag;
}
// 前置的++操作(a = ++b)
inline Complex& operator++(){
this->real += 1;
this->imag += 1;
return *this;
}
// 后置的++操作(a = b++;)
inline Complex operator++(int){
Complex tmp(*this);
tmp.real++;
tmp.imag++;
return tmp;
}
double real;
double imag;
};
/**
* 重载流输出
* @param _cout
* @param c
* @return
*/
ostream &operator<< (ostream &_cout, const Complex & c){
_cout << c.real << " + " <<c.imag <<"i";
return _cout;
}
int main() {
Complex C1(10, 1);
Complex C2(20, 2);
cout << C1 <<endl; // 调用operator<<
cout << ++C1 <<endl; // 调用operator++
cout << C1++ <<endl; // 调用operator++(int)
cout << C1 + C2 << endl;
Complex C3 = C2;
cout << C3 << endl;
bool _t = C3 == C3;
cout << _t << endl;
_t = C2 == C3;
cout << _t <<endl;
cout << (C3 != C2) << endl;
return 0;
}