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(); 
}

猜你喜欢

转载自www.cnblogs.com/hyq-lst/p/12897987.html