C++运算符重载学习笔记

#include<iostream>
using namespace std;
class Complex1
{
private: int a, b;
public:
    Complex1(Complex1 &obj){
        this->a = obj.getA();
        this->b = obj.getB();
        cout << "我是copy 构造函数" << "a:" << a << "\t b:" << b << endl;
    }
    Complex1(int a = 0, int b = 0)
    {
        this->a = a;
        this->b = b;
    }
    int getA(){
        return a;
    }
    int getB(){
        return b;
    }
    void show(){
        cout << "a:" << a << "\t b:" << b << endl;
    }
    friend Complex1 operator+(Complex1 &c1, Complex1 &c2);
    friend Complex1 operator++(Complex1 &c1);
     Complex1 operator-(Complex1 &c1)
    {
        Complex1 tmp;
        tmp.a = this->a - c1.a;
        tmp.b = this->b - c1.b;
        return tmp; 
    }
     Complex1 operator --(){
         this->a--;
         this->b--;
         return *this;
     }
     //全局函数 后置 ++ 
     friend Complex1 operator++(Complex1 &c2, int);

};

//全局函数后置++ 
Complex1 operator ++ (Complex1 &c2, int)
{
    //先使用C2 的属性,然后让属性++ 
    Complex1 tmp;
    tmp = c2;
    c2.a++;
    c2.b++;
    return tmp;

}

//Complex1 ComAdd(Complex1 &c1, Complex1 &c2)
//{
//  Complex1 tmp;
//  tmp.a = c1.a + c2.a;
//  tmp.b = c1.b + c2.b;
//  return tmp;
//}
Complex1 operator+(Complex1 &c1, Complex1 &c2)
{
    Complex1 tmp;
    tmp.a = c1.a + c2.a;
    tmp.b = c1.b + c2.b;
    return tmp;
}
Complex1 operator ++(Complex1 &c1)
{
    c1.a++;
    c1.b++;
    return c1;
}

//void mainhanshu()
//{
//  Complex1 c1(1, 2), c2(2, 3);
//  Complex1 c3 = ComAdd(c1, c2);
//  c3.show();
//  system("pause");
//}
Complex1 g(){
    Complex1 c1;
    return c1;
}
void main(){
    Complex1 c1(10, 20), c2(3, 4);
    //+ 运算符有两个参数 左操作数 和 右操作数 
    // 
    Complex1 c3 = c1.operator-(c2);
    c3.show();
    //目标 通过类的成员函数,完成操作符重载
    //1 要承认操作符重载是一个函数,要写函数原型
    //2 写出函数条用语言 c1.operator-(c2) 
    //3 完善函数原型
    c3++;
    c3.show();
    c3--; 
    c3.show();
    c3.operator--();

    c3.show();

    --c3;
    c3.show(); 

    //检查后置++ 
    Complex1 c4 = c3++; 
    c4.show();
    c3.show();

    system("pause");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值