运算符重载

来源:互联网 发布:js数组常用方法 编辑:程序博客网 时间:2024/05/17 08:30

一、操作符重载
用复数来实例:

#include <iostream>using namespace std;class Complex {public:    Complex (int r = 0, int i = 0) :m_r (r), m_i (i) {}    Complex const operator+ (Complex const& rhs) const {        Complex sum (m_r + rhs.m_r, m_i + rhs.m_i);        return sum;    }    void print (void) const {        cout << m_r << '+' << m_i            << 'i' << endl;    }private:    int m_r; // 实部    int m_i; // 虚部    friend Complex const operator- (Complex const& lhs, Complex const& rhs) {        return Complex (lhs.m_r - rhs.m_r, lhs.m_i - rhs.m_i);    }};

1.双目操作符
+/-
1)成员
Complex const operator+ (Complex const& rhs) const { … }
2)全局
Complex const operator+ (Complex const& lhs, Complex const& rhs) { … }
=/+=/-=
1)成员
Complex& operator+= (Complex const& rhs) {

return *this;
}
2)全局
Complex& operator-= (Complex& lhs, Complex const& rhs) {

return lhs;
}
2.单目操作符
-/~
1)成员
Complex const operator- (void) { … }
2)全局
Complex const operator~ (Complex const& c) { … }
前++/前–
1)成员
Complex& operator++ (void) {

return *this;
}
2)全局
Complex& operator– (Complex& c) {

return c;
}
后++/后–
1)成员
Complex const operator++ (int) { … }
2)全局
Complex const operator– (Complex& c, int) { … }“

0 0
原创粉丝点击