最近在学习 C++,所以顺便将每日所学记录下来,一方面为了巩固学习的知识,另一方面也为同样在学习C++的童鞋们提供一份参考。
运算符重载
重载的运算符是带有特殊名称的函数,函数名是由关键字 operator 和其后要重载的运算符符号构成的。与其他函数一样,重载运算符有一个返回类型和一个参数列表。
运算符重载,就是对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型。
你可以重定义或重载大部分 C++ 内置的运算符。例如 + 、 - 、 * 、 / 、
运算符重载基础
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
| class Complex { public: friend Complex operator+(Complex &c1, Complex &c2); Complex(int a, int b) { this->a = a; this->b = b; } void printCom() { cout<<a<<" + "<<b<<"i "<<endl; }
private: int a; int b; };
Complex operator+(Complex &c1, Complex &c2) { Complex c3(c1.a + c2.a, c1.b+c2.b); return c3; } void main() { { int a = 0, b = 0; int c = a + b; } Complex c1(1, 2), c2(3, 4);
Complex c3 = c1 + c2; c3.printCom();
system("pause"); }
|
成员或成员函数重载运算符
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 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
| #include "iostream" using namespace std;
class Complex { public: friend ostream& operator<<(ostream &out, Complex &c1); Complex(int a, int b) { this->a = a; this->b = b; } void printCom() { cout<<a<<" + "<<b<<"i "<<endl; } Complex operator-(Complex &c2) { Complex tmp(a - c2.a, this->b - c2.b); return tmp; } Complex operator+(Complex &c2) { Complex tmp(a + c2.a, this->b + c2.b); return tmp; } Complex& operator--() { this->a--; this->b--; return *this; } Complex& operator++() { this->a++; this->b++; return *this; }
Complex operator--(int) { Complex tmp = *this; this->a--; this->b--; return tmp; } Complex operator++(int) { Complex tmp = *this; this->a++; this->b++; return tmp; }
private: int a; int b; };
void main() {
Complex c1(1, 2), c2(3, 4);
Complex c3 = c1 + c2;
Complex c4 = c1 - c2; c4.printCom();
{ int a = 10, b = 1; int c = a + b; }
++c1; c1.printCom();
--c1; c1.printCom();
c1++; c1.printCom();
c1--; c1.printCom();
system("pause"); }
|