C++ 操作符重载笔记

#include <iostream>

using namespace std;

class Complex
{
public:
    Complex(){
        
    }
    Complex(int a,int b){
        this->a = a;
        this->b = b;
    }
    
    void printComplex()
    {
        cout <<"(" <<+ this->a << ", "<<this->b<<"i)"<<endl;
    }
    
    friend Complex complexAdd(Complex &c1,Complex &c2);
    
    Complex complexAdd(Complex &another)
    {
        Complex temp(this->a + another.a, this->b + another.b);
        return temp;
    }
    
    //friend Complex operator+(Complex &c1,Complex &c2);
    
    Complex operator+(Complex &c1)
    {
         Complex temp(this->a + c1.a,this->b + c1.b);
         return temp;
    }
    
    Complex& operator=(Complex &c1)
    {
        this->a = c1.a;
        this->b = c1.b;
        return *this;
    }
    
    
private:
    int a; //实数
    int b; //虚数
};

#if 0
Complex complexAdd(Complex &c1,Complex &c2)
{
    Complex temp(c1.a + c2.a,c1.b + c2.b);
    return temp;
}
#endif

//操作符重载写在全局
#if 0
Complex operator+(Complex &c1,Complex &c2)
{
    Complex temp(c1.a + c2.a,c1.b + c2.b);
    return temp;
}
#endif

int main(void){
    Complex c1(1,2);
    Complex c2(2,4);
    
  
    
    c1.printComplex();
    c2.printComplex();
    //Complex c3 = complexAdd(c1,c2);
    //Complex c3 = c1.complexAdd(c2);
    //Complex c3 = c1 + c2; //等价于operator+(c1,c2);
    //Complex c3 = c1.operator+(c2);
    Complex c3;
    c3= c1;
    c3.printComplex();
    

    
    
    
    return 0;
}
发布了27 篇原创文章 · 获赞 5 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/jfztaq/article/details/82380167