-
-
[分享]C++基础十五-运算符重载
-
2021-10-26 15:35 8165
-
运算符重载
函数重载可以让一个函数名有多种功能,在不同的情况下进行不同的操作。同理,运算符也可以重载,同一个运算符可以有不同的功能。
实际上,我们已经使用了运算符重载,例如使用 + 号对不同类型的数据进行加法运算,<< 既是位移运算符,又可以配合cout 向控制台输出数据。C++ 本身已经对这些运算符进行了重载,同时C++ 也允许程序员自己重载运算符。
运算符重载格式
1 2 3 4 | 返回值类型 operator运算符名称(形参表列) { / / TODO: } |
operator 是关键字,专门用于定义重载运算符的函数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | / / 定义一个复数类,使用运算符重载实现复数的加法运算 #include <iostream> using namespace std; class CComplex { public: CComplex(); CComplex(double real, double imag); public: / / 声明运算符重载 CComplex operator + (const CComplex& A) const; void Display() const; / / 重载输入运算符 friend istream& operator>>(istream& in , CComplex& C); / / 重载输出运算符 friend ostream& operator<<(ostream& out, CComplex& C); private: double m_dbReal; / / 实部 double m_dbImag; / / 虚部 }; CComplex::CComplex() : m_dbReal( 0.0 ), m_dbImag( 0.0 ) { } CComplex::CComplex(double real, double imag) : m_dbReal(real), m_dbImag(imag) { } / / 实现运算符重载 CComplex CComplex::operator + (const CComplex& A) const { return CComplex(this - >m_dbReal + A.m_dbReal, this - >m_dbImag + A.m_dbImag); } void CComplex::Display() const { cout << m_dbReal << " + " << m_dbImag << "i" << endl; } istream& operator>>(istream& in , CComplex& C) { in >> C.m_dbReal >> C.m_dbImag; return in ; } ostream& operator<<(ostream& out, CComplex& C) { out << C.m_dbReal << " + " << C.m_dbImag << "i" << endl; return out; } int main() { CComplex c1( 1.1 , 2.2 ); CComplex c2( 2.2 , 1.1 ); CComplex c3 = c1 + c2; c3.Display(); cin >> c1 >> c2; c3 = c1 + c2; cout << c3 << endl; return 0 ; } |
运算符重载其实就是定义一个函数,在函数体内实现想要的功能,当用到该运算符时,编译器会自动调用这个函数。也就是说,运算符重载是通过函数实现的,它本质上是函数重载,运算符重载函数除了函数名有特定的格式,其它地方和普通函数并没有区别。
运算符重载规则
- 运算符重载不能改变运算符的优先级和结合性。
- 运算符重载不会改变运算符的用法,操作数个数、操作数位置不变。
- 运算符重载不能有默认的参数,否则就改变了运算符操作数的个数。
- 运算符重载既可以作为类的成员函数,也可以作为全局函数,重载为全局函数需要声明为类的友元。
- 箭头运算符->、下标运算符[ ]、函数调用运算符( )、赋值运算符 = 只能以成员函数的形式重载。
- 长度运算符sizeof 、条件运算符 :? 、成员选择符 . 和域解析运算符 :: 不能被重载。
github:https://github.com/0I00II000I00I0I0
bilibili:https://space.bilibili.com/284022506
[培训]《安卓高级研修班(网课)》月薪三万计划,掌握调试、分析还原ollvm、vmp的方法,定制art虚拟机自动化脱壳的方法
赞赏
他的文章
[分享]C++基础十七-异常机制
7772
[分享]C++基础十六-模板
8123
[分享]C++基础十五-运算符重载
8166
[分享]C++基础十四-抽象类
7886
[分享]C++基础十三-多态
7618
看原图