C++-类的操作符(+)重写
使用const Complex operator + (const Complex &c ) const {} 重新定义类的+操作
#include<iostream> using namespace std; class Complex{ public: Complex(int r, int i):m_r(r),m_i(i){} void print(void){ cout << m_r << endl; cout << m_i << endl; } const Complex operator + (const Complex& c) const { Complex res(m_r + c.m_r, m_i + c.m_i); return res; } private: int m_r; int m_i; }; int main() { Complex c1(1, 2); Complex c2(2, 3); Complex c3 = c1 + c2; c3.print(); }
使用friend const Complex 来定义外函数
#include <iostream> #include <cstdio> using namespace std; class Complex{ public: Complex(int t, int r):m_r(r), m_t(t) {} void print(void) const { cout << m_r << "+" << m_t << endl; } //成员函数 //1)修饰返回结果,禁止对表达式再赋值 //2)常引用参数,支持常量型右操作数 //3)常函数,支持常量型左操作数 const Complex operator+(const Complex& c) const { Complex res(m_r + c.m_r, m_t + c.m_t); return res; } private: friend const Complex operator-(const Complex & l, const Complex &r); int m_r; int m_t; }; const Complex operator-(const Complex &l, const Complex &r){ Complex res(l.m_r - r.m_r, l.m_t - r.m_t); return res; } int main(void) { const Complex c1(1, 2); const Complex c2(2, 3); c1.print(); c2.print(); Complex c3 = c1 + c2; c3.print(); Complex c4 = c1 - c2; c4.print(); return 0; }
使用operator += 来定义 c1 += c2 函数
#include <iostream> using namespace std; class Complex { public: Complex(int r, int i):m_r(r), m_i(i){} void print(void) const { cout << m_r << "+" << m_i << endl; } Complex& operator +=(const Complex& c) { m_r += c.m_r; m_i += c.m_i; return *this; } friend Complex& operator -=(Complex& l, const Complex& r) { l.m_r -= r.m_r; l.m_i -= r.m_i; return l; } int m_r; int m_i; }; int main() { Complex c1(1, 2); Complex c2(2, 3); c1 += c2; c1.print(); c1 -= c2; c1.print(); }
每天更新pyQt5内容